Node.js & Express.js Series | Chapter 12 | Inserting record into database (POST API)
Welcome to chapter 12 of our Node.js & Express.js Series! In this chapter, we’ll be learning how to insert a record into a database using a POST API with Node.js and Express.js.
First, let’s set up our Node.js and Express.js environment. Make sure you have Node.js installed on your machine. If not, you can download it from the official website.
Next, create a new directory for your project and run the following command in your terminal:
npm init -y
npm install express
npm install body-parser
Now, let’s create a new file called app.js
and add the following code:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.post('/api/insertRecord', (req, res) => {
// Insert the record into the database
// You can use a database query library like Knex or Sequelize
res.status(200).send('Record inserted successfully');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Now, when you send a POST request to /api/insertRecord
with the record data in the request body, the server will insert the record into the database and send back a success message.
You can customize the /api/insertRecord
endpoint and the database insertion logic according to your specific requirements.
That’s it for chapter 12! In the next chapter, we’ll learn how to update a record in the database using a PUT API. Stay tuned!
hi @Anagh Technologies Inc, InsertOne callback not working for me, instead i tried promise it's working fine for me.