[英]How to move the API calls to server side from a working browser side website?
我正在使用 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;
};
不清楚您的服务器如何连接到您的前端,是通过 API 吗? 有反应吗? 所以我给你我能想到的最基本的答案,但试着带来更多的细节。
我假设您已经有一个 nodejs 服务器准备好发出这个请求。 The XMLHttpRequest belongs to browser's API and you can'y use it in Node.js, but there are two ways to do it: 1. Use the Node.js HTTP api 2. Use a lib
我认为了解 HTTP api 的工作原理非常重要,但我使用名为 Axios 的库为您提供简短答案。
const axios = require('axios')
const sendRequest = (method, url, data) => {
axios({
method,
url,
data
})
}
如前所述,节点没有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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.