Home > Net >  Express not sending a response
Express not sending a response

Time:05-08

I'm creating a backend for my application and basically, I'm reusing the code from my previous projects since I'm only setting it up at this point. However, the code that normally works, doesn't work right now.

Up until this point all I've done was to initialise npm, install dependencies I'm going to need and created my app.js file where I started setting up my backend. However, testing requests/responses turned out in postman sending the request and not responding whatsoever. I have been looking up the solution for this, but I can't seem to figure out why it's happening.

My app.js file

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

//app config
const app = express();
const port = process.env.PORT || 6299;

//middleware
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.json);
app.use(cors());
app.use((req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    next();
});
app.use((err, req, res, next) => {
    return res.json({ errorMessage: err.message });
});

//db config

//api endpoints
app.get('/', (req, res) => {
    res.status(200).send('Hello from the other sideeeee');
});

//listen
app.listen(port, () => {
    console.log(`Server started on port ${port}`);
});

Basically, for now it doesn't even send the response message, however my console logs that my server is up and running.

CodePudding user response:

because you used middleware but don't next()


const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

//app config
const app = express();
const port =  6299;

//middleware
// app.use(bodyParser.urlencoded({extended: true}));
// app.use(express.json);
// app.use(cors() );
app.use((req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    next();
});
app.use((err, req, res, next) => {
    return res.json({ errorMessage: err.message });
    next()
});

//db config

//api endpoints
app.get('/', (req, res) => {
    console.log(1011111111)
    res.status(200).send('Hello from the other sideeeee');
});

//listen
app.listen(port, () => {
    console.log(`Server started on port ${port}`);
});

CodePudding user response:

Maybe there is something wrong with browser postman try to use the windows app postman or use the rest client vscode extension

  • Related