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';///送信先
Http.open("POST", url);////////POSTでオープン。GETではContentsを送信できません。

let obj = {number:20, aaa:"ああああ"};////送信するJSON
Http.send(JSON.stringify(obj));////JSONをStringに変換して送信

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) => { /////Contentsを非同期で取得
      body.push(chunk);
    }).on('end', () => {
      body = Buffer.concat(body).toString();
      let obj = JSON.parse(body); ////文字列をJsonに戻す
    });
  } else{
    ///その他のRequestへの処理
  }
});

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をコピーしました