我的前端已成功连接到我的服务器;但是,我的初始获取请求是抛出:
GET http://localhost:8080/events net::ERR_EMPTY_RESPONSE
每次执行操作时,我的服务器都会抛出:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: res.json is not a function
这是我的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');
})
这是我的controller.js中的GET:
//Gets list of events
exports.listEvents = (req, res) => {
Event.find()
.then(events => {
res.json(events);
})
}
任何建议都会受到极大的欢迎!
答案 0 :(得分:1)
Event.find()
承诺失败。
没有捕获块来捕获错误。这就是UnhandledPromiseRejectionWarning
你可以回答这样的错误:
exports.listEvents = (req, res, next) => {
Event.find()
.then(events => {
res.json(events);
}).catch(err => { console.log(err); next(err) });
}
并在server.js中添加错误处理程序,如下所示:
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
});
});
这不会解决您的问题,只是告诉您问题所在。