【问题标题】:Error: Request failed with status code 400 - AXIOS NODEJS错误:请求失败,状态码为 400 - AXIOS NODEJS
【发布时间】:2022-02-14 00:01:50
【问题描述】:

我在通过 axios Error: Request failed with status code 400 连接 api 时遇到问题

有人可以帮帮我吗?

我的服务/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
    }
  }
}

【问题讨论】:

  • 看起来您正在发送内容类型为 application/x-www-form-urlencoded 的 JSON 数据 - 这里有问题。您的 API 真正期望什么样的数据?
  • API 需要 JSON 格式,所以我使用 JSON.stringify 进行转换。我使用相同的数据对 lib 请求进行了测试,它可以工作,但使用 axios 却无法工作
  • 我确实更改了我的标题,但也没有用。 const response = await api.post("api", JSON.stringify(data), { headers: { 'Content-Type': 'application/json', } } );

标签: node.js rest api express axios


【解决方案1】:

我在标题中添加了 'Content-Type': 'application / json' 并且它起作用了

【讨论】:

    【解决方案2】:

    你需要在路由中返回 res。

    而不是返回响应返回 res.status(200).json(response)

    【讨论】:

      猜你喜欢
      • 2021-01-12
      • 2021-04-07
      • 1970-01-01
      • 2020-08-30
      • 2020-10-21
      • 2021-04-12
      • 1970-01-01
      • 2017-06-02
      • 2020-03-29
      相关资源
      最近更新 更多