Getting 400 Bad Request on axios post call

Viewed 2576

I'm using a url shortner API to test connecting to a API and I keep getting a 400 BadRequest. I've read through a dozen posts here and tried all suggestions and still nothing will work. I don't know what I'm doing wrong.

Function

var axios = require('axios');

module.exports = function (callback, data) {

let url = 'https://cleanuri.com/api/v1/shorten';

let axiosConfig = {
    "headers": {
        'Content-Type': 'application/json;charset=UTF-8'
    }
};
  

let longUrl = { "url" : data };

axios(url, {
    method: "post",
    params: {
        "url" : data
    },
    headers: {
        "Accept": "application/json",
        "Content-Type": "application/json"
    }
})
.then(function (response) {
    callback(null, response.data);
}).catch(function (err) {
    console.log("error: " + err.response);
    callback(err, null);
});

I've also tried this and got same error

    axios.post(url, JSON.stringify(longUrl), axiosConfig)
.then(function (response) {
    callback(null, response.data);
}).catch(function (err) {
    console.log("error: " + err.response);
    callback(err, null);
});
1 Answers

To send data as body use data field on request options

const payload = { ... }
axios({ ..., data: payload })

params field is used to send query string within url

I have read your api docs https://cleanuri.com/docs. That requiring your payload send as body, so use data field

Here the snippet:

let payload = { "url" : data };

axios(url, {
    method: "post",
    data: payload,
    headers: {
        "Accept": "application/json",
        "Content-Type": "application/json"
    }
})

Edit: 400 Bad Request is indicating your request is invalid (by server)

Related