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