Node.js 错误:请求失败,状态代码为400-AXIOS NODEJS
我通过axios连接到api时遇到问题Node.js 错误:请求失败,状态代码为400-AXIOS NODEJS,node.js,rest,api,express,axios,Node.js,Rest,Api,Express,Axios,我通过axios连接到api时遇到问题错误:请求失败,状态代码为400 有人能帮我吗 我的服务/api.js:` const axios = require("axios"); const api = axios.create({ baseURL: "https://url.com" }); api.interceptors.request.use(async config => { config.headers.access_token = `token123`;
错误:请求失败,状态代码为400
有人能帮我吗
我的服务/api.js:`
const axios = require("axios");
const api = axios.create({
baseURL: "https://url.com"
});
api.interceptors.request.use(async config => {
config.headers.access_token = `token123`;
return config;
});
module.exports = api;
我的控制器:
const api = require('services/api');
router.post('/', async (req, res) => {
try {
const response = await api.post("/api", JSON.stringify(data));
return response;
} catch (err) {
return res.status(400).send({ erro: err })
}
})
module.exports = app => app.use('/routes', router)
但是当我提出请求时,我得到了错误
{
"erro": {
"message": "Request failed with status code 400",
"name": "Error",
"stack": "Error: Request failed with status code 400\n at createError (/Library/WebServer/Documents/api/node_modules/axios/lib/core/createError.js:16:15)\n at settle (/Library/WebServer/Documents/api/node_modules/axios/lib/core/settle.js:17:12)\n at IncomingMessage.handleStreamEnd (/Library/WebServer/Documents/api-nex/node_modules/axios/lib/adapters/http.js:236:11)\n at IncomingMessage.emit (events.js:228:7)\n at endReadableNT (_stream_readable.js:1185:12)\n at processTicksAndRejections (internal/process/task_queues.js:81:21)",
"config": {
"url": "/api",
"method": "post",
"data": "{"\myjson\": "\json\"}",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded",
"access_token": "token123",
"User-Agent": "axios/0.19.2",
"Content-Length": 398
},
"baseURL": "https://url.com",
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1
}
}
}
我在标题中添加了'Content Type':'application/json',效果很好您需要在路由中返回res
不是返回response return res.status(200).json(response)它看起来像是用
application/x-www-form-urlencoded
内容类型发送json数据-这里有些不对劲。您的API真正需要什么样的数据?API需要JSON格式,所以我使用JSON.stringify进行转换。我使用相同的数据对lib请求做了一个测试,它工作了,但在axios上它不工作。我确实更改了我的头,但也不工作。const response=await-api.post(“api”,JSON.stringify(数据),{headers:{'Content-Type':'application/JSON',}});