首页 > 解决方案 > SyntaxError:意外的标识符 Node.js

问题描述

我正在制作一个简单的 Web 应用程序并不断收到此错误。

app.get("/campground/:id/comments/new",function(req,res){
    camp.findById(req.params.id)({
        if(err)
            console.log(err);
        else        
            res.render("comments/new",{campground:camp});
    });
});

并不断收到此错误

 console.log(err);
 ^^^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

如果我删除错误处理,我得到错误,

res.render("comments/new",{campground:camp});
   ^

SyntaxError: Unexpected token .
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

任何人都可以帮忙吗?

标签: javascriptnode.js

解决方案


你没有findById正确使用,它应该有一个回调函数,像这样:

app.get("/campground/:id/comments/new",function(req, res, err){
    camp.findById(req.params.id, function(err, camp) {
        if(err) {
            console.log(err);
        } else {   
            res.render("comments/new",{campground:camp});
        }
    });
});

推荐阅读