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

この記事は約3分で読めます。
スポンサーリンク

Things I want to do

This code passes JSON data from the client-side JavaScript to the Node.js server.

スポンサーリンク

implementation

Client-side implementation

The client-side implementation is as follows:

The URL is the destination URL. Please change it as needed.

`obj` is the JSON (Object) to be sent.

const Http = new XMLHttpRequest();
const url='http://127.0.0.1/test';/// target
Http.open("POST", url);////////open with POST

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

Server-side implementation

Implement it as follows:

When the callback passed to createServer is called (when a Request arrives), the Request’s Body (Contents) has not yet arrived, so you need to set data and end events 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); ////convert string to json
    });
  } else{
    ///other process
  }
});

I was able to retrieve the values ​​on the server side as JSON, as shown below.

スポンサーリンク

Result

I was able to send JSON data from the client to the Node.js server.

スポンサーリンク

Websites I used as references

Get request body from node.js's http.IncomingMessage
I'm trying to implement a simple HTTP endpoint for an application written in node.js. I've created the HTTP server, but now I'm stuck on reading the request con...

コメント

タイトルとURLをコピーしました