0

My frontend is successfully connected to my server; however, my initial fetch request is throwing a:

GET http://localhost:8080/events net::ERR_EMPTY_RESPONSE

Every time I perform an action, my server is throwing:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: res.json is not a function

Here is my server.js:

// Require and initiate Express
const express = require('express');
const app = express();

//Import controllers, db and bodyParser
const controller = require('./controllers');
const bodyParser = require('body-parser');
const cors = require('cors');
require('./db');


//Add bodyParser & cors middleware
app.use(cors());
app.use(bodyParser.json());

//Define routes for List Events, Add Event, and Delete Event
app.get('/events', controller.listEvents);
app.post('/events', controller.addEvent);
app.delete('/events/:id', controller.deleteEvent);


//Initiate server on port 8080
app.listen(8080, () => {
  console.log('Server is listening on http://localhost:8080');
})

And here is the GET in my controller.js:

//Gets list of events
exports.listEvents = (req, res) => {
  Event.find()
  .then(events => {
    res.json(events);
  })
}

Any suggestions would be greatly received!

1
  • The Event.find() promise is failing. There's no catch block to catch the error. That's the reason for UnhandledPromiseRejectionWarning Commented Feb 17, 2018 at 12:49

1 Answer 1

1

The Event.find() promise is failing. There's no catch block to catch the error. That's the reason for UnhandledPromiseRejectionWarning

You can respond with error like this:

exports.listEvents = (req, res, next) => {
  Event.find()
  .then(events => {
    res.json(events);
  }).catch(err => { console.log(err); next(err) });
}

And add the error handler in the server.js like this:

app.use((err, req, res, next) => {
  res.status(err.status || 500).json({
    message: err.message || "Something went wrong. Please try again",
    status: err.status || 500
  });
});

This won't solve your issue, just tells you what the issue is.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Faizuddin, I've added the catch and it has revealed my problem is in fact in the front end. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.