简体   繁体   English

JavaScript / Express:TypeError:res.json不是函数

[英]JavaScript/Express: TypeError: res.json is not a function

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: 这是我的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: 这是我controller.js中的GET:

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

Any suggestions would be greatly received! 任何建议将不胜感激!

The Event.find() promise is failing. Event.find()承诺失败。 There's no catch block to catch the error. 没有捕获错误的捕获块。 That's the reason for UnhandledPromiseRejectionWarning 这就是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: 并在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
  });
});

This won't solve your issue, just tells you what the issue is. 这不会解决您的问题,仅告诉您问题是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM