【问题标题】:Syntax Error: unexpected Token {语法错误:意外令牌 {
【发布时间】:2016-10-31 14:51:59
【问题描述】:

这是我的模型:

var mongoose = require('mongoose');

var partySchema = new mongoose.Schema({
  partyCode: Number,
  partyName: String,
  mobileNo: String
});

var Party = module.exports = mongoose.model('Party', partySchema);

module.exports.getAllParties = function(callback){
  Party.find().lean().exec(function(err, parties){
    if (err) return callback(err, null);
    callback(null, parties);
  });
};

这是路线:

router.get('/', function(req, res, next){

  //retrieve all parties from Party model
  //mongoose.model('Party').find({}, function (err, parties) {
  Party.getAllParties(err, parties){
        if (err) {
            return console.error(err);
        } else {
            //respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
            res.format({

              //response in dust or jade files
              html: function(){
                  res.render('Party', {
                        title: 'Party',
                        "parties" : parties
                    });
              },

              //JSON response will show all parties in JSON format
              json: function(){
                  res.json(parties);
              }
          });
        }
  };
});

在 Route.js 的第 9 行(在上面的第 4 行代码中)我收到一个错误:

  Party.getAllParties(err, parties){

语法错误:{unexpected token

为什么会出乎意料?我不能在这里使用函数体吗???

【问题讨论】:

    标签: javascript node.js mongoose routes


    【解决方案1】:

    您需要传入一个函数。不幸的是,外面这样的块语句不起作用。

    这很可能是您需要的:

    Party.getAllParties(function (err, parties) {  
        // rest of your logic here
    });
    

    【讨论】:

    • 我已经尝试按照你说的执行,但是在浏览器中我得到一个错误,说没有定义派对。以及在命令提示符中我收到错误:未处理的拒绝错误:发送后无法设置标头。
    【解决方案2】:

    当你调用一个函数时,你不能在这些地方放置一个块语句。

    看起来你想要类似的东西

    Party.getAllParties(function() {
        // ...
    })
    

    传递匿名回调函数的地方

    【讨论】:

    • 我已经尝试按照你说的执行,但是在浏览器中我得到一个错误,说没有定义派对。以及在命令提示符中我收到错误:未处理的拒绝错误:发送后无法设置标头。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 2017-10-07
    • 2021-05-16
    相关资源
    最近更新 更多