Post form data with axios in Node.js

后端 未结 4 1936
一个人的身影
一个人的身影 2021-02-18 15:39

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

4条回答
  •  深忆病人
    2021-02-18 16:03

    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)
    })
    

提交回复
热议问题