[英]how to call API from axios with header
我想用 axios 調用 API POST方法,我用postman用頭配置做的,它返回結果
當我通過 axios 調用我的腳本時它返回錯誤,任何人都可以幫助我從 axios 方面做些什么?
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)
})
錯誤顯示
{
"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
}
似乎您將標題嵌套在另一個“標題”屬性中。 基本上你正在這樣做
headers: {
headers: {
'Content-Transfer-Encoding': ...
}
}
正如 Zai 在她的回答中顯示的那樣,您的問題是您的標頭變量:
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
是嵌套的,當你這樣做時:
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
你真正在做的是:
axios({
method: 'POST',
url: URL,
headers: headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
},
data : {
}
所以你的標題:而不是內容傳輸等......只是“標題”
嘗試這個:
const header = {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
另外,我建議你用你的 api 調用做一個 console.log,以便更快地發現這個問題並與郵遞員進行比較,這在開發階段真的很有幫助(只在本地使用它,永遠不要將該日志推送到生產環境)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.