简体   繁体   English

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

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

I'm testing out the Uber API on Postman, and I'm able to send a request with form data successfully.我正在 Postman 上测试 Uber API,并且能够成功发送带有表单数据的请求。 When I try to translate this request using Node.js and the axios library I get an error.当我尝试使用 Node.js 和 axios 库翻译此请求时,出现错误。

Here is what my Postman request looks like:这是我的邮递员请求的样子:

邮递员 POST 请求

The response I get is: { "error": "invalid_client" }我得到的响应是: { "error": "invalid_client" }

Here is what I'm doing in Node.js and axios:这是我在 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)
  })

When I do this, I get a 400 response.当我这样做时,我得到 400 响应。

I added the 'multipart/form-data' header because I filled out the form-data in the Postman request.我添加了'multipart/form-data'标头,因为我在 Postman 请求中填写了表单数据。 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?我希望得到与 Postman 相同的响应,我的 Node.js 脚本中的配置变量有问题吗?

Any help would be appreciated!任何帮助,将不胜感激!

You might be able to use Content-Type: 'application/x-www-form-urlencoded' .您也许可以使用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 .我在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)
})

You could also use a function to handle the translation to formUrlEncoded like so您还可以使用函数来处理转换为 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)
})

To send data with Content-Type application/x-www-form-urlencoded , wrap your {} with new URLSearchParams() .要使用 Content-Type application/x-www-form-urlencoded发送数据,请使用new URLSearchParams()包装您的{} Like this snippet:就像这个片段:

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


As for 10 June 2017, axios library does not support posting form data in Node.js.至于 2017 年 6 月 10 日, axios库不支持在 Node.js 中发布表单数据。 Here is the issue on GitHub - https://github.com/mzabriskie/axios/issues/789这是 GitHub 上的问题 - https://github.com/mzabriskie/axios/issues/789

We had the similar problem and decided to switch to request library.我们遇到了类似的问题,并决定切换到request库。

You can send multipart/form-data data with axios in Node by using FormData from the form-data library .您可以使用来自form-data libraryFormData在 Node 中使用 axios 发送multipart/form-data数据。 You still have to set some extra headers, like setting Content-Type to multipart/form-data , which you can do with FormData.getHeaders() :您仍然需要设置一些额外的标头,例如将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

From the error it seems your client_id or client_secret is incorrect.从错误看来,您的 client_id 或 client_secret 不正确。 Enable debugging and share the raw request/response (after filtering credentials out).启用调试并共享原始请求/响应(过滤凭据后)。

It is not true!这不是真的! You can post data with axios using nodejs.您可以使用 nodejs 通过 axios 发布数据。 I have done it.我已经做了。 The problem is, if you use PHP on the server side, there is a pitfall you need to be aware of.问题是,如果您在服务器端使用 PHP,您需要注意一个陷阱。 Axios posts data in JSON format (Content-Type: application/json) PHP's standard $_POST array is not populated when this content type is used. Axios 以 JSON 格式发布数据(内容类型:application/json) 使用此内容类型时,不会填充 PHP 的标准 $_POST 数组。 So it will always be empty.所以它永远是空的。 In order to get post parameters sent via a json request, you need to use file_get_contents(" http://php://input ") .为了获取通过 json 请求发送的 post 参数,您需要使用 file_get_contents(" http://php://input ") 。

A simple PHP script on the server side would be:服务器端的一个简单 PHP 脚本是:

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

Using this method you can avoid the formData dependency.使用这种方法可以避免 formData 依赖。 You CAN post data directly from node.js.您可以直接从node.js发布数据。

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

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