Home > front end >  Can't reach localhost:PORT created in Node.js and express
Can't reach localhost:PORT created in Node.js and express

Time:11-11

    require('dotenv').config();

const express = require('express');
const app = express();
const cors = require('cors');

app.use(cors);

const connectDB = require('./config/mongoDB');

const PORT = process.env.PORT || 8000;

// body parser
app.use(express.json({ extended: false }));

//router
app.use(
  '/',
  require('./routes/index')
);

app.listen(PORT, (req, res) => {
  connectDB();
  console.log('listening on port '   PORT);
});

so this is my express server code, it was working yesterday but I can't reach localhost: PORT (via postman and browser) today but it is running and listening to PORT. Where it goes wrong?

CodePudding user response:

  1. The cors middleware should be called with parenthesis, as a function:
app.use(cors());
  1. You are setting the body parser middleware incorrectly, change
app.use(express.json({ extended: false }));

to:

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
  • Related