I use axios to send a POST HTTP request with some binary data like this:
axios.post(url, input, {headers: {'Content-Type': 'application/octet-stream'}})
When I got an Bad request error I printed out the request headers:
"headers" : {
"common": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/octet-stream"
},
"delete": {},
"get": {},
"head": {},
"post": {
"Content-Type": "application/octet-stream"
},
"put": {
"Content-Type": "application/x-www-form-urlencoded"
},
"patch": {
"Content-Type": "application/x-www-form-urlencoded"
}
}
I overrode the default headers (see below) and got Ok instead Bad request
axios.defaults.headers = {"Content-Type": "application/octet-stream"}
So the problem is fixed but I don't like overriding axios defaults. How would you suggest use axios.post to send the header correctly ?
Related
The api call returns excel data as a readable stream. It was not possible to make a JSON from the response. How can I read out the data from the api call correctly?
return fetch(my_url, {
method: "GET",
headers: headers,
}).then(response => response);
response.json() // Cou not read data, endend up in catch block
response.body
ReadableStream {locked: false}
locked: false
response header
{
"access-control-allow-origin": "*",
"cache-control": "no-cache",
"connection": "close",
"content-disposition": "attachment; filename=tabelle.xlsx",
"content-length": "6085",
"content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"date": "",
"server": ""
}
I'm trying to understand how the Discord API works, and I'm struggling to send a message in a channel. the code executes fine, but the message is not being sent. I tried with this code:
await request(`https://discord.com/api/v9/channels/${channel_id}/messages`, {
method: "POST",
body: content,
headers: this.headers,
});
but it doesn't work. What am i doing wrong?
content is the string I want to send, it's a function parameter and so is channel_id.
headers is:
{
authorization: `Bot ${token}`,
accept: "*/*",
};
The request returns a status code of 400 (Bad request).
I solved it. The issue is that I didn't specify the Content-Type of the request, and passed the content as a string. I added to the headers: "content-type": "application/json", and to the body I passed a Json object of the content:
await request(`https://discord.com/api/v9/channels/${channel_id}/messages`, {
method: "POST",
headers: this.headers,
body: json({ content }),
});
And the headers:
this.headers = {
authorization: `Bot ${token}`,
"content-type": "application/json",
};
I want to call the API POST method with axios, I did it with postman with header configuration like, and it return the results
and the body request looks :
it return error when I call by axios this my script, anyone can help me what I suppose todo from the axios side ?
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
})
.then((response) => {
if (response.status !== 200) {
return res.send(respone("500", response.data.result.data))
} else {
return res.send(respone("200", response.data.result.data))
}
})
.catch((error) => {
console.log(error);
return res.send(error)
})
the error show
{
"message": "Request failed with status code 404",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Content-Transfer-Encoding": "application/json",
"HTTP_API_KEY": "xxxx",
"User-Agent": "axios/0.27.2",
"Content-Length": 2
},
"method": "post",
"url": "xxxxx",
"data": "{}"
},
"code": "ERR_BAD_REQUEST",
"status": 404
}
It seems you nested your headers inside another "headers" property.
Basically you're doing this
headers: {
headers: {
'Content-Transfer-Encoding': ...
}
}
As Zai showed in her answer you problem is your header variable:
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
is nested, when you do this:
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
what you are really doing is:
axios({
method: 'POST',
url: URL,
headers: headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
},
data : {
}
So your header: instead of being Content-transfer etc... is just 'headers'
try this:
const header = {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
also, i recommend you to do a console.log with your api call in order to find this problems faster and compare with postman, really helpful in develop phase (just use it in local, never push that log to production)
Seems like a simple issue but everywhere else suggested adding "application/json" in 'headers' which I have tried.
'Accept'and 'Content-Type' are both "application/json".
Also tried both json and stringfy 'Body' but keep getting 415 on Chrome extension JavaScript.
textArraySample = ["sample","sample2"];
var serverUrl = "https://webappcontentnotification.azurewebsites.net/api/ContentUpload";
const body={
"textbatch":textArraySample,
"userId": userId,
"url": window.location.href
}
let result =
fetch(serverUrl, {
method: 'POST',
mode: "no-cors",
headers: {
'Accept': "application/json",
'Content-Type': "application/json"
},
body: JSON.stringify(body)
})
.then(response => {
console.log('response:', response);
})
.catch((error) => {
console.log('Error:', error);
});
Update: seems like "Content-Type" is not correctly set
Did not see this mentioned somewhere else.
The root cause is that "Content-Type" cannot be set to "application/json" while using "Mode: no-cors".
link here
mode: "no-cors" only allows a limited set of headers in the request:
Accept
Accept-Language
Content-Language
Content-Type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain
I am having a problem sending an authorization header with dropzonejs
this.componentConfig = {
iconFiletypes: ['.jpg', '.png', '.gif'],
showFiletypeIcon: true,
postUrl: `${getBaseUrl()}/Controller/ImportImage`,
headers: {
'Authorization': 'Bearer'
},
};
<DropzoneComponent config={config} eventHandlers={eventHandlers} djsConfig={djsConfig}> </DropzoneComponent>
Based on the code the headers are define like:
var headers = {
"Accept": "application/json",
"Cache-Control": "no-cache",
"X-Requested-With": "XMLHttpRequest"
};
So, defining like
headers: { "Authorization" : "Bearer AbCdEf123456" }
should work.