Declare variables from post request node js

Please tell me how I can declare variables that come to the server (node ​​js) using post request. Now I use this code and get this content:

name=Test&ip=192.168.0.1

How can I declare a variable and assign a value to it that would be like this:

var name = "Test"; 
var ip = "192.168.0.1";

The code I use:

var http = require("http");
http.createServer(function(request, response){
    if (request.method === 'POST') {
        let body = '';
        request.on('data', chunk => {
            body += chunk.toString(); // convert Buffer to string
        });
        request.on('end', () => {
            console.log(body);
        });
    }
    response.end()
}).listen(3000);

Upvotes: 1

Views: 638

Answers (1)

Timo Reymann
Timo Reymann

Reputation: 895

Thats pretty easy using URLSearchParams:

const http = require("http");

http.createServer(function(request, response){
  // only post is allowed
  if (request.method !== 'POST') {
     response.end()
     return
  }

  let body = '';
  request.on('data', chunk => {
     body += chunk.toString()
  })

  request.on('end', () => {
     const params = new URLSearchParams(body)
     let name = params.get("name")
     let ip = params.get("ip")

     response.write(JSON.stringify({
        name,
        ip
     }))
     response.end()
   })
}
}).listen(3000)

I inserted it into a simple wrapper using JSON.stringify to return the response using a simple json.

Of course there is missing input validation and so on ...

Upvotes: 2

Related Questions