fini
fini

Reputation: 146

How can I use HTTP POST data on nodejs server?

I am using Google Cloud Function and want to process the data provided by the post request.

On the website:

        const Http = new XMLHttpRequest();
        const url='https://us-central1-finitest-4aafb.cloudfunctions.net/create-user1';
        Http.open("POST", url);
        Http.send("name=Negan&password=Lucille");

        Http.onreadystatechange = (e) => {
            console.log(Http.responseText)
        }

On the server:

exports.helloWorld = (req, res) => {
  res.set('Access-Control-Allow-Origin', "*");
  res.set('Access-Control-Allow-Methods', 'GET, POST');

  let message = 'User created ' + req.body.user;
  res.status(200).send(message);
};

How can I use the "name=Negan&password=Lucille" data on the server?

Upvotes: 1

Views: 552

Answers (2)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

Since you are using a POST request with XMLHttpRequest(), you need to get the parameters via the body of the request, as follows:

exports.helloWorld = functions.https.onRequest((req, res) => {
    res.set('Access-Control-Allow-Origin', "*");
    res.set('Access-Control-Allow-Methods', 'GET, POST');

    console.log(req.body);
    console.log(req.body.name);
    console.log(req.body.password);

    let message = 'User created ' + req.body.name;
    res.status(200).send(message);
});

More details in the doc.

You also need, on the frontend, to send the proper content-type (i.e. application/x-www-form-urlencoded) along with the request, as follows:

    const Http = new XMLHttpRequest();
    const url='https://us-central1-finitest-4aafb.cloudfunctions.net/helloWorld';
    Http.open("POST", url);

    // send the proper header information along with the request
    Http.setRequestHeader(
      'Content-type',
      'application/x-www-form-urlencoded'
    );

    Http.send("name=Negan&password=Lucille");

    Http.onreadystatechange = (e) => {
        console.log(Http.responseText)
    }

If you want to get them as query string parameters, as explained by Ashish Kumar, you need to add them to the URL, not via send(), since you use a POST.

    const url='https://us-central1-finitest-4aafb.cloudfunctions.net/create-user1';
    Http.open("POST", url + "?name=Negan&password=Lucille");  // Note the ?
    Http.send();

In this case you can use req.query.name.

More details in the result of this search: https://www.google.com/search?client=firefox-b-d&q=XMLHttpRequest.send%28%29+POST+querystring


Finally, be aware that with https://us-central1-finitest-4aafb.cloudfunctions.net/create-user1 you are NOT calling your helloWorld Cloud Function, but a create-user1 Cloud Function.

Upvotes: 2

Ashish
Ashish

Reputation: 46

Those are called request query and they can be accessed via req.query object. So in your case you can access the data as

req.query.name
req.query.password

Upvotes: 1

Related Questions