How to set `Content-Type` in headers in Axios? - axios

I'm having trouble setting the Content-Type header in axios.
Here's my code:
axios({
url: fetchUrl,
data: JSON.stringify(fetchOptions.body),
method: 'POST',
headers: {
'Content-Type': 'application/vnd.api+json',
Accept: 'application/vnd.api+json',
},
})
And here's the request headers:
Accept is set correctly but Content-Type is not. (Confirmed by removing Accept in my code, in which case the request header reverts to json isntead of vnd.api+json.)
When I change Content-Type to ContentType, then I see ContentType in the Response headers, so the problem is specifically with Content-Type.

It turns out that this error was the result of having an empty data; the property was called data, but I mistakenly called body:
axios({
url: fetchUrl,
data: JSON.stringify(fetchOptions.data),
method: 'POST',
headers: {
'Content-Type': 'application/vnd.api+json',
Accept: 'application/vnd.api+json',
},
})

Related

Flutter http with authorisation: ClientException (Failed to parse header value)

I have an API that expects a JWT token.
I tested the API with https://hoppscotch.io, here is the query that returns the expected results (no error)
import axios from "axios";
const options = {
method: 'POST',
url: 'https://my_authority/text-message',
headers: {
Authorization: 'Bearer my_token',
'content-type': 'application/json'
},
data: {message: ''}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
And here is the code in Dart that fires the error ClientException (Failed to parse header value):
await http.post(
Uri.parse('$_httpEndpoint/$path'),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer my_token',
},
body: jsonEncode(body));
Both queries have the same parameters. I have no clue about the root causes.
Here is requests.headers in locals for IOClient.send when the error fires:
_CompactLinkedCustomHashMap ({content-type: application/json; charset=utf-8, authorization: Bearer my_token})
I don't know why http adds charset=utf-8, and I didn't manage to remove it.
I looked over the internet and didn't find an answer. Most of the similar questions are related to an error in the backend, it is not the case here.

Can't override some HTTP headers with github.request() in actions/github-script workflow script

My workflow's script with action/github-script(v6) step:
const response = await github.request('POST https://example.com', {
headers: {
authorization: 'Bearer xxx',
accept: 'application/vnd.heroku+json; version=3', // I want header to be like this
'content-type': 'application/json'
},
// some other options, like request body...
});
console.log(response);
When the accept and other HTTP headers are automatically overriden with:
{
status: 400,
reponse: {}, // not important, body complains about incorrect Accept header
request: {
method: 'POST',
url: 'example.com',
headers: {
accept: 'application/vnd.github.-preview+json', // wtf?
authorization: 'token [REDACTED]', // wtf? it should start with "Bearer"
'content-type': 'application/json', // ok, as expected
'user-agent': 'actions/github-script octokit-core.js/3.5.1 Node.js/16.13.0 (linux; x64)' // ok, but I didn't set this...
},
// other stuff...
}
Now the question is what am I missing? Can I make truthly custom request using github.request() api like that?

"Content-Type" and "Content-Encoding" headers in axios

I am using axios#0.21.1 and I want to validate the response headers.
I am unable validate the headers "Content-Type" and "Content-Encoding" from a GET response.
"Content-Type": No matter what content-type i pass in request, the content-type in response is always application/JSON.
Example Code Snippet:
if (<token is present>) {
request.headers = {
authorization : 'Bearer ${token}'
}
} else {
config.auth = {}
}
config.headers = Object.assign(config.header, {
'content-type': application/<custom content>,
'accept-encoding': 'gzip, deflate, br'
}
await axios.get(endPoint, config)
.then(response => {
return response
}*
When i am checking response.header, i see that content-type is showing as "application/json" instead of the custom type. But when i hit the same url in POSTMAN i could see that content-type is as expected.
Content-Encoding: I want to validate the content-encoding in the response, but what i learnt is axios does not return content-encoding header in the response and when i check their github, they are asking to use axios.interceptors. I tried using interceptors but still i am not seeing the header in response. But this header is present in response when i try in POSTMAN. There have been some solution say CORS needs to be enabled in server side. I am strictly asking it from QA point of view because we cannot enable CORS in server side.
Any help is highly appreciable.
Try:
axios.post(your-url, {
headers: {
'Content-Encoding': 'gzip'
}
})
or
axios.post(your-url, {
headers: {
'Accept-Encoding': 'gzip',
}
})
This is by design: https://axios-http.com/docs/req_config
I also ran into this and couldn't find a solution. Ended up using node-fetch instead.

Dio options.contentType vs header "Content-Type"

I was trying to make a call to a REST service using the Dio plugin, but kept getting HTTP 400 response code. I thought I was doing everything right by setting the content type and response type options to JSON:
Response response = await Dio().get(
'https://api.example.com/v1/products/$productId',
queryParameters: {},
options: Options(
contentType: ContentType.json,
responseType: ResponseType.json,
headers: {'Authorization': 'Bearer $MY_API_KEY'}
),
);
However, it turns out that I needed to add a Content-Type header as well:
headers: {'Authorization': 'Bearer $MY_API_KEY'}, 'Content-Type': 'application/json' };
So now I'm confused - what exactly does the contentType option do? I thought it was analogous to setting the Content-Type header manually?
I've tried this locally using dio: ^3.0.10 and it seems that ContentType.json is an invalid value for contentType.
Digging through the documentation for dio, Headers.jsonContentType should be used.

Ionic Changes Content-Type

Ok I have to make a simple GET request that work in Postman but not in the Ionic code. I have determined that the reason is that the API treats incoming requests differently based on Content-Type. application/json works text doesn't.
headers: {
"Content-Type": 'application/json; charset=UTF-8',
"Accept": 'application/json; charset=UTF-8'
},
As you can see I'm setting the header to try to force application/json but when I sniff the request it has changed to text/html somehow. How do I force Ionic to take my Content-Type as definitive?
I managed to get it to work with the following headers
var headers = {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Methods" : "POST, GET, OPTIONS, PUT",
"Content-Type": "application/json",
"Accept": "application/json"
};