Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a POST request from node.js Express?

Could someone show me the simplest way to send a post request from node.js Express, including how to pass and retrieve some data? I am expecting something similar to cURL in PHP.

like image 599
Chong Lip Phang Avatar asked Sep 01 '15 09:09

Chong Lip Phang


People also ask

How do you send a POST request in node JS?

Note: If you are going to make GET, POST request frequently in NodeJS, then use Postman , Simplify each step of building an API. In this syntax, the route is where you have to post your data that is fetched from the HTML. For fetching data you can use bodyparser package. Web Server: Create app.

How do I send a POST request URL?

POST request in itself means sending information in the body. I found a fairly simple way to do this. Use Postman by Google, which allows you to specify the content-type (a header field) as application/json and then provide name-value pairs as parameters. Just use your URL in the place of theirs.

What is Express () in node JS?

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.


Video Answer


1 Answers

var request = require('request');  function updateClient(postData){             var clientServerOptions = {                 uri: 'http://'+clientHost+''+clientContext,                 body: JSON.stringify(postData),                 method: 'POST',                 headers: {                     'Content-Type': 'application/json'                 }             }             request(clientServerOptions, function (error, response) {                 console.log(error,response.body);                 return;             });         } 

For this to work, your server must be something like:

var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json())  var port = 9000;  app.post('/sample/put/data', function(req, res) {     console.log('receiving data ...');     console.log('body is ',req.body);     res.send(req.body); });  // start the server app.listen(port); console.log('Server started! At http://localhost:' + port); 
like image 178
Gautam Avatar answered Sep 23 '22 00:09

Gautam