我的前端已成功连接到我的服务器;但是,我最初的获取请求抛出:
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);
})
}
如有任何建议,我们将不胜感激!
最佳答案
Event.find()
promise 失败。
没有 catch block 来捕获错误。这就是 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
});
});
这不会解决您的问题,只是告诉您问题是什么。
关于JavaScript/Express : TypeError: res. json 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841372/