Passing JSON data from a client to a Node.js server

This article can be read in about 3 minutes.

The purpose 

Passing JSON data from client-side JavaScript to a Node.js server.

Implementation

Client-side implementation

The client-side implementation will be as follows.

The url variable represents the destination URL and should be modified as needed.

The obj variable represents the JSON object (in O

const Http = new XMLHttpRequest();
const url='http://127.0.0.1/test';///Destination
Http.open("POST", url);////////open for POST. GET method cannot send Contents

let obj = {number:20, aaa:"ああああ"};////JSON to send 
Http.send(JSON.stringify(obj));////convert from JSON to String, then send it

Server-side implementation

The implementation will be as follows:

When the callback passed to createServer is invoked (when a Request arrives), the Request’s body (contents) has not yet been received. Therefore, it’s necessary to set data and end event listeners for the request.

const server = http.createServer((req, res) => {

if (req.url == "/test") {
    let body = [];
    req.on('data', (chunk) => { /////get Contents with async
      body.push(chunk);
    }).on('end', () => {
      body = Buffer.concat(body).toString();
      let obj = JSON.parse(body); //// from string to json
    });
  } else{
    ///process for other request 
  }
});

The server successfully retrieved the following JSON data.

Result

we are able to successfully send JSON data from the client to the Node.js server.

Reference

Forbidden - Stack Exchange

コメント

Copied title and URL