[英]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.