[英]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.