首页 > 解决方案 > 如何将 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;
};

标签: javascriptnode.js

解决方案


如前所述 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));

推荐阅读