简体   繁体   中英

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. 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

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? 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. 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.

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

node-fetch resource: 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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