无法从NodeJs Server Express获得响应

时间:2018-10-10 10:05:28

标签: javascript node.js

大家好。每当页面加载时,我都会从前端Java脚本调用get方法。问题是我的网页JavaScript中没有得到该get请求的响应。每当加载chatroom.hbs来向该用户显示聊天室中的所有现有聊天记录时,我都会调用getChats方法,但是似乎我没有从服务器获得对该请求的响应。这些是我项目中的文件

chatroom.js

task1

app.js

var express = require('express');
var router = express.Router();
var obj = require('../bin/www');
var db = require('../databaseModels');

/* GET users listing. */
router.get('/:uName', function(req, res, next) {
  res.render('chatroom', {title: 'Welcome to Chat Room', userName: 
  req.params.uName});
});

// save a new chat message in database
router.post("/putChats", async (req, res) => {
try {
  var chat = new db.Chats(req.body)
  await chat.save()
  res.sendStatus(200)
  //Emit the event
  obj.io.emit("chat", req.body)
} 
catch (error) {
  res.sendStatus(500)
  console.error(error)
}
})

// Get chat messages from detabase and return to client
router.get("/getChats", (req, res) => {
  db.Chats.find({}, (error, chats) => {
  res.send(chats)
})
})

// clear method for clearing the chats
router.post("/clear", function(){
// Remove all chats from collection
   db.Chats.remove({}, function(){
   obj.io.emit('cleared');
 });
})

module.exports = router;

chatroom.hbs

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require("body-parser");
var hbs = require('express-handlebars');
var indexRouter = require('./routes/index');
var chatroomRouter = require('./routes/chatroom');

var app = express();

// view engine setup
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout', layoutsDir: __dirname + '/views/'}))
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    next();
});

app.use('/', indexRouter);
app.use('/chatroom', chatroomRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

0 个答案:

没有答案