javascript - 在 Node.js 中使用 axios 发布表单数据

标签 javascript node.js post uber-api axios

我正在 Postman 上测试 Uber API,并且能够成功发送带有表单数据的请求。当我尝试使用 Node.js 和 axios 库翻译此请求时,出现错误。

这是我的 Postman 请求的样子:

Postman POST request

我得到的响应是:{ "error": "invalid_client"}

这是我在 Node.js 和 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)
  })

当我这样做时,我会收到 400 响应。

我添加了 'multipart/form-data' header ,因为我在 Postman 请求中填写了表单数据。如果没有标题,我会得到相同的结果。

我希望得到与 Postman 相同的响应,我的 Node.js 脚本中的配置变量有问题吗?

任何帮助将不胜感激!

最佳答案

您也许可以使用 Content-Type: 'application/x-www-form-urlencoded'。我遇到了与 https://login.microsoftonline.com 类似的问题,它无法处理传入的 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)
})

你也可以使用一个函数来处理转换为 formUrlEncoded 像这样

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

关于javascript - 在 Node.js 中使用 axios 发布表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41764184/

相关文章:

javascript - 检测任何 ajax 调用何时失败

javascript - 如何模拟 JEST 中 SUT 中使用的方法上使用的装饰器函数

javascript - jQuery 选择器到 Javascript 的转换

javascript - 在对象解构中使用默认值,同时保留任何非默认值

node.js - 为什么 Safari 和 Chrome 上的 Socket.io 连接速度慢

ruby-on-rails - Ruby - cURL 为 nil :NilClass error 抛出未定义的方法 `post'

java - Android 上使用 Volley-api 进行 http 请求

javascript - 无法读取未定义的属性 'errorCallback'

node.js - Docker 和 node_modules - 将它们放在一个层或一个卷中?

node.js - 当logstash服务器断开连接时,nodejs中出现ECONNREFUSED错误