aurelia-fetch-client create request headers on the fly

只谈情不闲聊 提交于 2019-12-10 16:44:28

问题


I am using aurelia-fetch-client to send some data to a web-api (in a register method).

headers: Headers;

register() {

    this.headers = new Headers();

    this.headers.append("content-type", "application/json; charset=utf-8");

    this.httpClient.fetch("api/Account/Register", {
        method: "POST",
        body: JSON.stringify({
            email: this.email,
            password: this.password
        }),

        headers: this.headers
    })
}

As you see, I want to update the headers of my request (in that append method call) and for doing that I need to create my own Headers object, to call the method append on it and then to assign it to the headers property of my request. I want to do that directly in the request body: instead of writing

 headers: this.headers

I want to write something like:

 headers: { 
    append("content-type", "application/json; charset=utf-8");
 }

or something like:

  headers: new Headers().append(..)

The idea is to avoid declaring a new object for storing my headers. How can I do that?

Thank you respectfully.


回答1:


You can just pass in an JS object literal with the keys and values directly to the headers property:

this.httpClient.fetch("api/Account/Register", {
    method: "POST",
    body: JSON.stringify({
        email: this.email,
        password: this.password
    }),

    headers: {
       "content-type", "application/json; charset=utf-8"
    }
});

Or you can also crate the Headers object pre-filled with your custom headers:

this.httpClient.fetch("api/Account/Register", {
    method: "POST",
    body: JSON.stringify({
        email: this.email,
        password: this.password
    }),

    headers: new Headers({
       "content-type", "application/json; charset=utf-8"
    })
});

See also the headers related test of the plugin.



来源:https://stackoverflow.com/questions/32202012/aurelia-fetch-client-create-request-headers-on-the-fly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!