Post form data with axios in Node.js

Mike picture Mike · Jan 20, 2017 · Viewed 48.3k times · Source

I'm testing out the Uber API on Postman, and I'm able to send a request with form data successfully. When I try to translate this request using Node.js and the axios library I get an error.

Here is what my Postman request looks like:

Postman POST request

The response I get is: { "error": "invalid_client" }

Here is what I'm doing in Node.js and axios:

var axios = require("axios");

const config = { headers: { 'Content-Type': 'multipart/form-data' } };

axios.post('https://login.uber.com/oauth/v2/token', {
  client_id: '***',
  client_secret: '***',
  grant_type: 'authorization_code',
  redirect_uri: 'http://localhost:8080/',
  code: '***'
}, config)
  .then(function(response) {
    console.log(response.data)
  })
  .catch(function(error) {
    console.log(error)
  })

When I do this, I get a 400 response.

I added the 'multipart/form-data' header because I filled out the form-data in the Postman request. Without the header I get the same result.

I'm expecting to get the same response I'm getting from Postman, is there something wrong with my config variable in the Node.js script?

Any help would be appreciated!

Answer

Reid Evans picture Reid Evans · Sep 4, 2018

You might be able to use Content-Type: 'application/x-www-form-urlencoded'. I ran into a similar issue with https://login.microsoftonline.com where it was unable to handle incoming application/json.

var axios = require("axios");

axios({
  url: 'https://login.uber.com/oauth/v2/token',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  data: `client_id=${encodeURIComponent('**')}&client_secret=${encodeURIComponent('**')}&grant_type=authorization_code&redirect_uri=${encodeURIComponent('http://localhost:8080/')}&code=${encodeURIComponent('**')}`
})
.then(function(response) {
  console.log(response.data)
})
.catch(function(error) {
  console.log(error)
})

You could also use a function to handle the translation to formUrlEncoded like so

const formUrlEncoded = x =>
   Object.keys(x).reduce((p, c) => p + `&${c}=${encodeURIComponent(x[c])}`, '')

var axios = require("axios");

axios({
  url: 'https://login.uber.com/oauth/v2/token',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  data: formUrlEncoded({
     client_id: '***',
     client_secret: '***',
     grant_type: 'authorization_code',
     redirect_uri: 'http://localhost:8080/',
     code: '***' 
  })
})
.then(function(response) {
  console.log(response.data)
})
.catch(function(error) {
  console.log(error)
})