Node.js web service using Express

To create a Node.js web service using Express that handles POST requests with parameters, you can follow these steps:

1. Initialize a new Node.js project:

mkdir myWebService
cd myWebService
npm init -y

2. Install Express and Body-Parser:

npm install express body-parser

3. Create an index.js file with the following code:

// index.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

// Use body-parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Handling POST request with parameters
app.post('/api', (req, res) => {
  const { param1, param2 } = req.body;
  res.send(`Received POST data - Parameter 1: ${param1}, Parameter 2: ${param2}`);
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

4. Run the service using the following command:

node index.js

With this setup, the Express server listens for POST requests at the /api endpoint and retrieves the parameters param1 and param2 from the request body.

You can test this setup using tools such as cURL or Postman by sending a POST request to http://localhost:3000/api with JSON data containing param1 and param2 as key-value pairs.

Komentar

Postingan populer dari blog ini

OTP (One Time Password) functionality in PHP with an expiration time

Read text from an image in Node.js

Get row id on datatable.row on each javascript