javascript - 如何将 API 调用从工作的浏览器端网站移至服务器端?
问题描述
我正在使用 javascript 发出 POST 请求,当我在浏览器index.html
中打开文件并单击已链接到以下代码的“POST”按钮时,它工作正常。但是,我想把它移到服务器端,由于网上有很多帖子,我对如何做到这一点感到困惑?任何帮助表示赞赏。
这是我的工作 js 代码,它以 JSON 格式返回值
const sendRequest = (method, url, data) => {
const promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader(
"accessToken",
"AB 1234"
);
xhr.setRequestHeader("requestId", "req");
xhr.setRequestHeader("deviceId", "dev");
xhr.responseType = "json";
if (data) {
xhr.setRequestHeader("Content-Type", "application/json");
}
xhr.onload = () => {
if (xhr.status >= 400) {
reject(xhr.response);
} else {
resolve(xhr.response);
}
};
xhr.onerror = () => {
reject("Something went wrong!");
};
xhr.send(JSON.stringify(data));
});
return promise;
};
解决方案
如前所述 node 没有XHR
,但您应该能够通过使用请求重新实现请求而无需付出很大的努力
节点获取资源:https ://github.com/node-fetch/node-fetch
示例请求:
const fetch = require('node-fetch');
const body = {a: 1};
fetch('https://httpbin.org/post', {
method: 'post',
body: JSON.stringify(body),
headers: {'Content-Type': 'application/json'}
})
.then(res => res.json())
.then(json => console.log(json));
推荐阅读
- azure - 使用 Xamarin.iOS 的 Azure Active Directory 身份验证过程
- javascript - 商店补水完成后如何更新 App.js 中的状态?
- xml - Nifi SplitXML 和 EvaluateXPath 性能和内存使用情况?
- javascript - 将模块设置为 ES2017 时出现 tsconfig 错误
- c# - 如何运行通过 SqlCommand 声明语句的 SQL?
- kubernetes - Kubernetes 中服务的完全限定域名 (FQDN) 不起作用?DNS-1035
- java - IDEA 编码文件不正确,我打开的每个文件都损坏了
- algorithm - 使用自定义距离函数对数百万个字符串进行模糊搜索
- node.js - EnvironmentVariableTarget.Process 在进程结束后继续存在
- json - 保留一些 json 键值对,同时使用 jolt 转换它们