简体   繁体   中英

Am I correctly using the request module in NodeJS?

I need to make an POST request of type "application/json" to some URL

Here is the request format

{
  "Subject": "TestSubject",
  "Body": "TestBody",
  "PreferredLanguage": "en-US",
  "Recipients": [
    {
      "FirstName": "TestName",
      "EmailAddress": "TestEmail"
    }
  ]
}

Here is how I am doing this in my code with the request module, which is not currently working.

request.post(
        'https://someURL.com/messages',
        {
            json:
            {
                Subject: "TestSubject",
                Body: "TestBody",
                PreferredLanguage: "en-US",
                Recipients: [
                    {
                        FirstName: "TestName",
                        EmailAddress: "TestEmail"
                    }
                ]
            }
        }
    )

What is wrong with how I am doing this request?

Your code is missing the callback

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

As explained here: npmjs requests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM