How can I make an outbound HTTP POST request, with data, in node.js?
相关问题
- Angular RxJS mergeMap types
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- HTML form is not sending $_POST values
- Google Apps Script: testing doPost() with cURL
- How to instantiate Http service in main.ts manuall
I found a video which explains on how to achieve this: https://www.youtube.com/watch?v=nuw48-u3Yrg
It uses default "http" module together with "querystring" and "stringbuilder" modules. The application takes two numbers (using two textboxes) from a web page and upon submit, returns sum of those two (along with persisting the values in the textboxes). This is the best example I could find anywhere else.
This is the simplest way I use to make request: using 'request' module.
Command to install 'request' module :
Example code:
You can also use Node.js's built-in 'http' module to make request.
To Post Rest/JSON Request
We can simply use request package and save the values we have to send in Json variable.
First install the require package in your console by npm install request --save
This my solution for
POST
andGET
.About the
Post
method:If the body is a JSON object, so it's important to deserialize it with
JSON.stringify
and possibly set theContent-Lenght
header accordingly:before writing it to the request:
About both
Get
andPost
methods:The
timeout
can occur as asocket
disconnect, so you must register its handler like:while the
request
handler isI strongly suggest to register both the handlers.
The response body is chunked, so you must concat chunks at the
data
handler:At the
end
thebody
will contain the whole response body:It is safe to wrap with a
try
...catchthe
JSON.parse` since you cannot be sure that it is a well-formatted json actually and there is no way to be sure of it at the time you do the request.Module:
SimpleAPI
Usage:
For those coming here in the later years. There are now a wide variety of different libraries that can accomplish this with minimal coding. I much prefer elegant light weight libraries for HTTP requests unless you absolutely need control of the low level HTTP stuff.
One such library is Unirest
To install it, use
npm
.$ npm install unirest
And onto the
Hello, World!
example that everyone is accustomed to.Extra:
A lot of people are also suggesting the use of request [ 2 ]
It should be worth noting that behind the scenes
Unirest
uses therequest
library.Unirest provides methods for accessing the request object directly.
Example:
I like the simplicity of superagent (https://github.com/visionmedia/superagent). Same api on both node and browser.
2018 edit: lately, though, I've moved to using node-fetch (https://www.npmjs.com/package/node-fetch), which has an api that matches
fetch
from the browsers.