I want to set the header Content-type: application/json
in all my requests to my backend in Angular2. I use this in my main app.js
file.
let headers = new Headers({
'Content-Type', 'application/json'
})
class MyOptions extends BaseRequestOptions {
headers: headers
}
bootstrap(App, [
provide(RequestOptions, {useClass: MyOptions}),
ROUTER_BINDINGS,
HTTP_PROVIDERS,
bind(APP_BASE_HREF).toValue('/')
])
I'm expecting all uses of Http
to use the new content-type, but this code still has the content-type set to text/plain
saveMaster (master) {
return this.http
.put(`${config.API_URL}/masters/${master._id}`, JSON.stringify(master))
.map(res => res.json())
}
I have to manually set the headers for each request to get it work correctly. Am I doing something wrong?
Note: I want to set a header option globally, not have to set it with every request type like is found in this solution.
In the Name field, enter the name of your header rule (for example, My header ). From the Type menu, select Request, and from the Action menu, select Set. In the Destination field, enter the name of the header affected by the selected action. In the Source field, enter where the content for the header comes from.
Custom headers allow site owners to upload their own “title” image to their site, which can be placed at the top of certain pages. These can be customized and cropped by the user through a visual editor in the Appearance > Header section of the admin panel. You may also place text beneath or on top of the header.
HTTP Headers let the client and the server share additional information about the HTTP request or response. For example, we use the content-type header to indicate the media type of the resource like JSON, text, blob, etc.
MyOptions
to:class MyOptions extends RequestOptions {
constructor() {
super({
method: RequestMethod.Get,
headers: new Headers({
'Content-Type': 'application/json',
'X-Some-Header': 'some-content'
});
});
}
}
provide(RequestOptions, {useClass: MyOptions})
AFTER HTTP_PROVIDERS
(otherwise default BaseRequestOptions
will be used instead of your MyOptions
).bootstrap(App, [
// ...
HTTP_PROVIDERS,
provide(RequestOptions, {useClass: MyOptions}) // <- after HTTP_PROVIDERS!!!
])
See this plunk
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With