DEV Community

Adeyemi Raji
Adeyemi Raji

Posted on

To set up a Node.js server with an Express web framework and a PostgreSQL database using Sequelize, you can follow these steps:

1.First, make sure you have Node.js and PostgreSQL installed on your system. If you don't have them already, you can download and install them from their respective websites.

2.Create a new Node.js project by running the following command in your terminal:

npm init -y

Enter fullscreen mode Exit fullscreen mode
  1. Install the required dependencies by running the following command:
npm install express sequelize pg

Enter fullscreen mode Exit fullscreen mode
  1. Create a new file called server.js and add the following code to it:
const express = require('express');
const Sequelize = require('sequelize');

const app = express();

// Connect to the database
const sequelize = new Sequelize('database_name', 'username', 'password', {
  host: 'localhost',
  dialect: 'postgres'
});

// Test the connection to the database
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection to the database has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

// Define your model(s)
const User = sequelize.define('user', {
  firstName: {
    type: Sequelize.STRING
  },
  lastName: {
    type: Sequelize.STRING
  }
});

// Create a table for the model(s)
sequelize.sync()
  .then(() => {
    console.log('Tables created successfully');
  })
  .catch(err => {
    console.error('Error creating tables:', err);
  });

// Start the server
app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Enter fullscreen mode Exit fullscreen mode
  1. Replace database_name, username, and password with the appropriate values for your PostgreSQL database.

  2. Run the server by executing the following command:

node server.js

Enter fullscreen mode Exit fullscreen mode
  1. Your server should now be up and running, and you should be able to interact with the database using Sequelize. You can use the User model to create, read, update, and delete records in the users table. For example, you can add the following code to your server file to create a new user in the users table:
app.post('/users', (req, res) => {
  User.create({
    firstName: 'John',
    lastName: 'Doe'
  })
    .then(user => {
      res.send(user);
    })
    .catch(err => {
      res.status(500).send(err);
    });
});

Enter fullscreen mode Exit fullscreen mode

So for testing of your endpoints, you can make use of tool such postman for. I hope this helps.

Top comments (0)