Interface for http headers in the fetch method - javascript

I have a method that fires a fetch function. It also sets headers over which type I would like to have control.
// Request headers
let headers: HttpHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
// Checks if user have x-auth-token cookie
const token = getCookie(AUTH.COOKIE_NAME);
if (token !== null) {
headers = {
...headers,
[AUTH.API_TOKEN]: token
};
}
// Request body
const request = {
method,
headers,
body: JSON.stringify(body)
};
if (body || method.toUpperCase() === HttpMethod.GET) {
delete request.body;
}
I have also enum, which holds all allowed headers:
export enum HttpHeader {
ACCEPT = 'Accept',
CONTENT_TYPE = 'Content-Type',
X_AUTH_TOKEN = 'x-auth-token'
}
I already know that you can't specify enum as the expected index value in the ts interface. Can you give me another option to control http request headers? I saw the idea of using an array of objects, but I have the impression that it is a bit of a form over content.

You can use an enum to define a type that has all the enum values as keys using a mapped type (what you can't do is have an enum as an index parameter).
The predefined Record and Partial mapped types will do the job nicely:
type HttpHeaders = Partial<Record<HttpHeader, string>>
export enum HttpHeader {
ACCEPT = 'Accept',
CONTENT_TYPE = 'Content-Type',
X_AUTH_TOKEN = 'x-auth-token'
}
// Request headers
let headers: HttpHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
headers = {
...headers,
[HttpHeader.X_AUTH_TOKEN]: "token"
};
Play

Related

axios - why can't I override the request header

const config = {
headers: {
'Content-Type': 'application/json',
accept: 'application/json',
},
baseURL: 'https://my-site.com',
};
const axiosInstance = axios.create({config});
// override here
const result = await axiosInstance.get('url', {
headers: { Authorization: 'Bearer ' + accessToken, Accept: '*/*' },
params: {}
})
In the request header, Accept still shows the 'application/json' instead of */*, while the Authorization shows correct value.
How to override the header in axiosInstance.get?
Update
My problem is similar to https://github.com/axios/axios/issues/1819
This happens because you set the accept header instead of the Accept header. In the first case, the value is appended to the default. In the second case, the value is replaced.
Demo link: https://codesandbox.io/s/mystifying-einstein-0ye2gq

400 Error despite working in Postman, possible reasons?

I am using the Deepl API, and when I run the request in Postman it is successful, however using it in my app it returns only a 400 Error, which I assume means the headers aren't set up correctly, but it is just how it is in my Postman. Can anyone point out what may be the issue here?
async translateMessage(data = {}) {
const url = "https://api.deepl.com/v2/translate?auth_key=myAuthKey";
const response = await fetch(url, {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*'
},
body: {
text: JSON.stringify(this.text),
target_lang: 'DE',
source_lang: 'EN'
}
});
return response.json();
},
Example HTTP Post Request from Documentation:
POST /v2/translate?auth_key=[yourAuthKey]> HTTP/1.0
Host: api.deepl.com
User-Agent: YourApp
Accept: */*
Content-Length: [length]
Content-Type: application/x-www-form-urlencoded
auth_key=[yourAuthKey]&text=Hello, world&source_lang=EN&target_lang=DE
The body property of a URL-encoded message (with the application/x-www-form-urlencoded content type) must be either a string of the query parameters, or a URLSearchParams instance.
Solution
Pass the object of key/value pairs to the URLSearchParams constructor.
You might as well add auth_key (one of the required query parameters) to that, and remove it from the URL.
Remove JSON.stringify() from the text property as that would insert unnecessary quotes into the translation.
const url = 'https://api.deepl.com/v2/translate';
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*'
}, 1️⃣
body: new URLSearchParams({
auth_key: myAuthKey, 2️⃣
text: this.text, 3️⃣
target_lang: 'DE',
source_lang: 'EN'
})
});

Why is Axios not using the Content-Type header and converting the request method to GET when PATCHing to a specific URL?

I have inherited a codebase using Axios, and I am otherwise unfamiliar with the library. This is a Node application, and I'm attempting to send a PATCH request to a third party API. Axios is configured using the following:
const axios = require('axios').create({
baseURL: process.env.API_URL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
auth: {
username: process.env.API_USER,
password: process.env.API_PW,
},
});
I then try to make the following PATCH request:
const data = {
fields: {
field_a: 'yes',
field_b: 'no',
},
};
try {
const res = await axios.patch(`/user/${user.id}`, data, {
headers: {
'Content-Type': 'application/json'
}
});
return res;
} catch (err){
console.error(err);
}
From what I can see I'm just redefining the Content-Type header when making the patch call, but that was just an attempt to figure this out. It doesn't work either way. What I see in the response object's config property is the following (most of it is excluded):
{
headers: {
Accept: "application/json"
User-Agent: "axios/0.19.0"
},
method: 'patch',
}
Looking at the request property of the same response object I see that the method there is listed as "GET" with the Content-Type header also not listed there. It appears as though the Content-Type header is being stripped and the method is being changed to GET.
If I change nothing but the URL destination to /userWRONGPATH/${user.id} I receive, as expected, a 404 response, but the response object's config data includes this:
{
headers: {
Accept: "application/json"
Content-Length: 105
Content-Type: "application/json"
User-Agent: "axios/0.19.0"
}
}
The response object's request method is now the expected 'PATCH'. I am unsure why the patch method would work for other paths if that is in fact what is happening here.
Hello I think that the problem could be related of send the header again in Axios you define a config and that is added to all the requests.
This is an example that I use to order the project with axios.
// Axios custom config
const axiosInstance = axios.create({
baseURL: urlBase,
// timeout: 1000,
headers: { 'Content-type': 'application/json' },
});
export const apiPatchRequest = (url, id, obj) => (
axiosInstance.patch(`${url}/${id}`, obj)
);

HttpParams set null for call

I have a problem with HttpParams and HttpHeaders after migrating my project from Angular 7 to Angular 8. When I call the API the params are not added. If anyone can help me fix this problem it will be great.
Here is the method in which I define the headers as well as the params.
fetchJson(url: string, parameters ? : any) {
this.token = this.cookieService.get('access_token');
this.contrat_token = this.cookieService.get('contrat_token');
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('Authorization', 'Bearer ' + this.token);
headers = headers.append('contrat_token', this.contrat_token);
let params = new HttpParams()
params.set('search', parameters);
console.log('les headers');
console.log(headers);
console.log('params');
console.log(params.toString())
return this._http.get(url, {
headers,
params
}).pipe(map((resp: any) => {
if (resp.status === 401 || resp.status == 401 || resp.status.toString() == "401") {
this.clearCookie();
} else {
let reponse = resp;
if (reponse == -1 || reponse == "-1") {
this.router.navigate(["/"]);
}
}
return resp;
}
And I call this method in my services as follows.
getDetailThematiquePrevNext(id: string, typeBase: string) {
let URL = this.urlDecorator.urlAPIDecorate("DI", "GetDetailThematiqueHeaderPrevNext");
let params = this.urlDecorator.generateParameters({
id: id,
typeBase: typeBase,
});
return this.apiFetcher.fetchJson(URL, params);
}
Reason provided by Cue is correct, You need to use chaining or do what you did for headers
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('Authorization', 'Bearer ' + this.token);
headers = headers.append('contrat_token', this.contrat_token);
let params = new HttpParams()
params = params = params.set('search', parameters);
More readable way to write this would be as follows
const headers = new HttpHeaders()
.append('Content-Type', 'application/json')
.append('Authorization', 'Bearer ' + this.token)
.append('contrat_token', this.contrat_token);
const params = new HttpParams().set('search', parameters);
Also, you can drop Content-Type header, as it is json by default
Probably due to lazy parsing. You have to do a get or getAll to access values to determine the state.
HttpParams class represents serialized parameters, per the MIME type application/x-www-form-urlencoded. The class is immutable and all mutation operations return a new instance.
HttpHeaders class represents the header configuration options for an HTTP request. Instances should be assumed immutable with lazy parsing.
You may want to pass your options directly into the instance for both headers and params:
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.token,
'contrat_token': this.contrat_token
});
let params = new HttpParams({
search: parameters
});
As #Siraj stated in an answer, there are alternative ways to set values for headers and params such as set...
let headers = new HttpHeaders().set('name', 'value');
let params = new HttpParams().set('name', 'value');
Or append...
let headers = new HttpHeaders().append('name', 'value');
let params = new HttpParams().append('name', 'value');
The important thing to note here is that these methods require chaining otherwise each method creates a new instance.
You could also convert objects like so:
let headerOptions = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.token,
'contrat_token': this.contrat_token
}
let headers = new HttpHeaders();
Object.keys(headerOptions).forEach((key) => {
headers = headers.set(key, headerOptions[key]);
});
It's also worth avoiding any binding of objects by reference, and instead pass as parameters:
return this._http.get(url, {
headers: headers,
params: params
});
And finally, because your type annotation is "any" for the parameters argument, params expects HttpParamsOptions which is a key/value object where values must be a string annotation.
let params = new HttpParams({
search: JSON.stringify(parameters)
});
Try console.log(params.getAll('search')) but, to make sure headers and params are sent, a better place to check will be Network tab in DevTools.

Send data in a http post in angular 2?

I'm trying to send data with http post following differents threads, but I can't do it.
I need to send this data, tested in postman.
Headers.
Content-Type: application/x-www-form-urlencoded
Authorization: Basic user:pass
Body.
grant_type: password
scope: profile
This is my code.
login() {
let url = URL_LOGIN;
let headers = new Headers(
{
'Content-Type': 'application/json',
'Authorization': 'Basic user:pass'
});
let body = {
'grant_type': 'password',
'scope': 'profile'
}
return this.http.post(url, body, { headers: headers })
.map((response: Response) => {
var result = response.json();
return result;
})
}
Thanks in advance!!
There are two things you need to modify:
Your headers passed into the http post method missed one step. It should contain the following:
let options = new RequestOptions({ headers: headers });
Ensure you import RequestOptions from #angular/http
Then pass options into your post method as follows:
return this.http.post(url, body, options)...
The http post method body can only be a string. Therefore, it should be as follows:
let body = 'grant_type=password' + '&scope=profile';

Categories