Error: Request failed with status code 400 - AXIOS NODEJS
Asked Answered
E

3

6

I have a problem connecting to the api by axios Error: Request failed with status code 400

Can someone help me please?

My services/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;

My controller:

 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)

But while I make the request, I get the error

{
  "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
    }
  }
}
Ecclesiasticus answered 27/2, 2020 at 13:9 Comment(3)
It looks like you're sending JSON data with application/x-www-form-urlencoded content type - something's not right here. What kind of data does your API really expect?Pudding
The API expects JSON format so I used JSON.stringify to convert. I did a test with lib request using the same data and it worked but with axios it didn't workEcclesiasticus
I did change in my headers but didn't work too. const response = await api.post("api", JSON.stringify(data), { headers: { 'Content-Type': 'application/json', } } );Ecclesiasticus
E
2

I added 'Content-Type': 'application / json' in the headers and it worked

Ecclesiasticus answered 28/2, 2020 at 15:58 Comment(0)
V
0

Don't use JSON.stringify(data) it adds \ and " in the data which creates weird behaviour. Simply add 'Content-Type': 'application/json' in headers and directly pass the JSON data. Here is the updated code:

const api = require('services/api');
router.post('/', async (req, res) => {    
   try {
     const response = await api.post("/api", data, {
       headers: {
         'Content-Type': 'application/json'           
       }
     });
     return res.status(200).send(response.data);
    } catch (err) {          
      return res.status(400).send({ erro: err })
    }
})
Venality answered 2/10 at 10:45 Comment(0)
A
-1

You need to return res as you is in a route.

Instead of returning response return res.status(200).json(response)

Alyssa answered 16/1, 2021 at 17:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.