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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With