For creating Http Get or Http Post Server using Nodejs (Not consuming Get or Post) Follow instructions below:
First Create a Nodejs project by running:
npm init -y
Then install express and body-parser dependencies by running
npm i express body-parser
Now create and edit the index.js file and add below code for serving Get & Post requests:
const express = require("express");
const bodyParser = require("body-parser");
const router = express.Router();
const app = express();
// add router in express app
app.use("/", router);
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
//sample Get Server
router.get('/', function (req, res) {
res.send('hello world')
});
//sample Post Server
router.post('/', (req, res) => {
req.on('data', function (data) {
res.writeHead("200", "OK");
res.end("end");
console.log("Getting JSON!")
let result = JSON.parse(data.toString());
console.log(data.toString());
})
});
app.listen(6000, () => {
console.log("Started on PORT 6000");
})
For running the code just simply run:
node index.js
Then you can test your code by calling curl commands:
curl http://localhost:6000
curl –request POST ‘http://localhost:6000’ \
–header ‘Accept: application/json’ \
–header ‘Content-Type: text/plain’ \
–data-raw ‘{“id”: “1”}’