繁体   English   中英

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

[英]Post form data with axios in Node.js

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

这是我的邮递员请求的样子:

邮递员 POST 请求

我得到的响应是: { "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 脚本中的配置变量有问题吗?

任何帮助,将不胜感激!

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

要使用 Content-Type application/x-www-form-urlencoded发送数据,请使用new URLSearchParams()包装您的{} 就像这个片段:

const axios = require("axios");
axios
  .post("https://api.zipwhip.com/user/login", new URLSearchParams({
  username: "hello",
  password: "byby",
}))
  .then((res) => console.log(res.data));


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

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

您可以使用来自form-data libraryFormData在 Node 中使用 axios 发送multipart/form-data数据。 您仍然需要设置一些额外的标头,例如将Content-Type设置为multipart/form-data ,您可以使用FormData.getHeaders()来完成:

const axios = require('axios');
const FormData = require('form-data');

const form = new FormData();
form.append('my_field', 'my value');
form.append('my_other_field', 'my second value');

axios.post('http://example.com', form, { headers: form.getHeaders() })

现在在 axios 文档中使用多种解决方案清楚地记录了此用例: https ://axios-http.com/docs/urlencoded#form-data

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

这不是真的! 您可以使用 nodejs 通过 axios 发布数据。 我已经做了。 问题是,如果您在服务器端使用 PHP,您需要注意一个陷阱。 Axios 以 JSON 格式发布数据(内容类型: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发布数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM