Reputation: 204
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!
Upvotes: 0
Views: 5411
Reputation: 4328
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.
Upvotes: 1