简体   繁体   English

如何将 API 调用从工作的浏览器端网站移至服务器端?

[英]How to move the API calls to server side from a working browser side website?

I am using javascript to make a POST request, and it works fine when I open my index.html file in the browser and click on the 'POST' button that I have linked to the following code.我正在使用 javascript 发出 POST 请求,当我在浏览器中打开我的index.html文件并单击我已链接到以下代码的“POST”按钮时,它工作正常。 However, I would like to move this to server side and due to the numerous posts online I am confused as to how to do that?但是,我想把它移到服务器端,由于网上有很多帖子,我对如何做到这一点感到困惑? Any help is appreciated.任何帮助表示赞赏。

This is my working js code which returns the values in JSON format这是我的工作 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;
};

It's not clear how your server connects to your front-end, is it through an API?不清楚您的服务器如何连接到您的前端,是通过 API 吗? Is it react?有反应吗? So I'm giving you the most basic answer I could think of, but try to bring more details.所以我给你我能想到的最基本的答案,但试着带来更多的细节。

I'm assuming you already have a nodejs server ready to make this request.我假设您已经有一个 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 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

I think is very important to know how the HTTP api works, but I'm giving you the short answer using a lib called Axios.我认为了解 HTTP api 的工作原理非常重要,但我使用名为 Axios 的库为您提供简短答案。

const axios = require('axios')

const sendRequest = (method, url, data) => {
 axios({
   method,
   url,
   data
 })
}

As stated node does not have XHR , but you should be able to re-implement the request without a great deal of effort by using a request如前所述,节点没有XHR ,但是您应该能够通过使用请求来重新实现请求而无需付出很大的努力

node-fetch resource: https://github.com/node-fetch/node-fetch节点获取资源: https://github.com/node-fetch/node-fetch

Example Request:示例请求:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM