Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript节点获取用法_Javascript_Nodes - Fatal编程技术网

Javascript节点获取用法

Javascript节点获取用法,javascript,nodes,Javascript,Nodes,我可以通过此代码请求获取数据 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',

我可以通过此代码请求获取数据

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);