Syntax Error: expected token n

I am learning how to use the MEAN stack and practice. I am involved in a network that asks you for your name, email address and course that you recently did. Then it saves the information in the database. I can’t find the error, and possibly easily.

var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var morgan = require('morgan'); var mongoose = require('mongoose'); var port = process.env.PORT || 8080; var Schema = mongoose.Schema; var User = require('./user'); app.use(bodyParser.urlencoded({ extended: true})); app.use(bodyParser.json()); mongoose.connect('mongodb://localhost'); app.use(morgan('dev')); var apiRouter = express.Router(); apiRouter.route('/') .post(function(req, res) { var user = new User(); user.name = req.body.name; user.course = req.body.course; user.mail = req.res.mail; user.save(function(err) { console.log(user.name); res.json({ message: 'Thank you!'}); }); }).get(function(req, res) { User.find(function(err, users) { if (err) res.send(err); res.json(users); }); res.json({ message: 'YEAAAAHHHH!'}); }); app.use('/', apiRouter); app.listen(port); console.log('Magic happens on port' + port); 

And this is user.js:

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ name: {type: String, required: true}, course: {type: String, required: true}, mail: {type: String, required: true} }); module.exports = mongoose.model('User', UserSchema); 

Thanks !: D

EDIT: sorry, I forgot to put an error:

 SyntaxError: Unexpected token n at parse (/Users/pingu/Documents/mean_project/node_modules/body-parser /lib/types/json.js:83:15) at /Users/pingu/Documents/mean_project/node_modules/body-parser/lib/read.js:116:18 at invokeCallback (/Users/pingu/Documents/mean_project/node_modules/raw-body/index.js:262:16) at done (/Users/pingu/Documents/mean_project/node_modules/raw-body/index.js:251:7) at IncomingMessage.onEnd (/Users/pingu/Documents/mean_project/node_modules/raw-body/index.js:308:7) at emitNone (events.js:67:13) at IncomingMessage.emit (events.js:166:7) at endReadableNT (_stream_readable.js:905:12) at nextTickCallbackWith2Args (node.js:474:9) at process._tickCallback (node.js:388:17) 
+6
source share
1 answer

Unexpected token is an error message generated by JSON.parse , so you

  • telling your server to wait for JSON and
  • does not provide valid JSON.

This is because you supply the Content-type: application/json header in your request, but you supply urlencoded data of the type form in your body, for example name=foobar&course=baz&...

Just remove the JSON Content-type so that your server correctly parses the body as form data.

+10
source

All Articles