Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aurelia-fetch-client create request headers on the fly

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.

like image 577
Cosmin Ioniță Avatar asked Feb 10 '23 05:02

Cosmin Ioniță


1 Answers

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.

like image 194
nemesv Avatar answered Mar 12 '23 04:03

nemesv