簡體   English   中英

Javascript 節點獲取用法

[英]Javascript node-fetch usage

我可以通過此代碼的請求獲取數據。

let request = require('request');
let options = {
   'method': 'POST',
   'url': 'https://example.com/api',
   'headers': {
       'Content-Type': 'application/x-www-form-urlencoded'
   },
   form: {
       'client_id': '12345678',
       'client_secret': 'abcdefg'
   }
};
request(options, function (error, response) {
   if (error) throw new Error(error);
   console.log(response.body);
});

但是,當我使用“fetch”訪問相同的 API 時,我得到了“404.00.001”。 這段代碼有什么問題嗎?

const fetch = require("node-fetch");

const url = "https://example.com/api";

var headers = {
  'Content-Type': 'application/x-www-form-urlencoded'
};

var data = JSON.stringify( {
  'client_id': '12345678',
  'client_secret': 'abcdefg'
});

fetch(url, {method: 'POST', headers: headers, body: data})
  .then(response => response.json())
  .then((resp) => {
     console.log(resp);
  })
  .catch(error => console.error('Unable to fetch token.', error));

'Content-Type': 'application/x-www-form-urlencoded'沒有說 JSON 那么為什么你有var data = JSON.stringify

文檔告訴您如何將數據編碼為表單參數。

 const { URLSearchParams } = require('url'); const params = new URLSearchParams(); params.append('a', 1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM