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

问题描述 投票:12回答:4

我正在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'标头,因为我在Postman请求中填写了表单数据。没有标题我得到相同的结果。

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

任何帮助,将不胜感激!

javascript node.js post uber-api axios
4个回答
11
投票

你也许可以使用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)
})

4
投票

截至2017年6月10日,axios图书馆不支持在Node.js中发布表单数据。这是关于GitHub的问题 - https://github.com/mzabriskie/axios/issues/789

我们有类似的问题,并决定切换到request库。


1
投票

从错误看,您的client_id或client_secret似乎不正确。启用调试并共享原始请求/响应(在过滤凭证后)。


0
投票

这不是真的!您可以使用nodejs使用axios发布数据。我已经做了。问题是,如果你在服务器端使用PHP,你需要注意一个陷阱。 Axios以JSON格式发布数据(Content-Type:application / json)使用此内容类型时,不会填充PHP的标准$ _POST数组。所以它总是空的。为了获得通过json请求发送的post参数,你需要使用file_get_contents(“http://php://input”)。

服务器端的简单PHP脚本是:

if($_SERVER['REQUEST_METHOD']==='POST' && empty($_POST)) {
 $_POST = json_decode(file_get_contents('http://php://input'));
}

使用此方法可以避免使用formData依赖项。您可以直接从node.js发布数据。

© www.soinside.com 2019 - 2024. All rights reserved.