所以我做這個教程https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4當我當我嘗試啓動服務器我得到這個錯誤語法錯誤:意外的令牌節點JS教程
/server.js:84
.put(function(req, res) {
^
SyntaxError: Unexpected token .
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
,這是我的代碼看起來像
// server.js
var router = express.Router(); // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next){
// do logging
console.log('For every request this message is being shown.');
next(); // make sure we go to the next routes and don't stop here
});
// test route to make sure everything is working
router.get('/', function(req, res){
res.json({ message: 'Whatsup Welcome to my first node api!'});
});
// more routes for our API will continue here
// on routes that end in /Bears
router.route('/bears')
// create a bear (accessed at POST http://localhost:8080/bears)
.post(function(req, res) {
var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear has been born!' });
});
})
// get all the bears (accessed at GET http://localhost:8080/api/bears)
.get(function(req, res) {
Bear.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
// on routes that end in /bears/:bear_id
// ------------------------------------------------
router.route('/bears/:bear_id')
// get all the bears (accessed at GET http://localhost:8080/api/bears/:bear_id)
"line :84 ->>>" .get(function(req, res) {
Bear.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
// update the bear with this id (accessed at PUT http://localhost:8080/api/bears/:bear_id)
.put(function(req, res) {
// use our bear model to find the bear we want
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
bear.name = req.body.name; // update the bears info
// save the bear
bear.save(function(err) {
if (err)
res.send(err); }
res.json({ message: 'Bear updated!' });
});
});
});
// REGISTER OUR ROUTES here
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE server
app.listen(port);
console.log('Magic is happening on port:' + port);
無論你用什麼來編輯你的代碼,都應該支持某種內置的「linting」(驗證你的語法),它會突出顯示這些容易犯的錯誤。 你甚至可以使用免費的在線工具,如[jsFiddle](http://jsfiddle.net),[CodePen](http://codepen.io)等,把你的JS,「整理」它是一致的格式和可讀性,並突出顯示任何錯誤。這裏是[CodePen中的代碼](http://codepen.io/greglockwood/pen/yNrqYO?editors=001),它向您顯示右下方的一個小錯誤圖標,您可以點擊查看違規行。 – GregL