簡體   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