Express Node Server中的“SyntaxError:意外的令牌n”

时间:2015-12-28 18:48:07

标签: angularjs node.js express

我收到此错误 -

SyntaxError: Unexpected token n
    at parse (/Users/afroza/node_modules/body-parser/lib/types/json.js:83:15)
    at /Users/afroza/node_modules/body-parser/lib/read.js:116:18
    at invokeCallback (/Users/afroza/node_modules/raw-body/index.js:262:16)
    at done (/Users/afroza/node_modules/raw-body/index.js:251:7)
    at IncomingMessage.onEnd (/Users/afroza/node_modules/raw-body/index.js:308:7)
    at IncomingMessage.emit (events.js:104:17)
    at _stream_readable.js:908:16
    at process._tickCallback (node.js:355:11)

我创建了一个带有nodejs的路由,我收到了这个错误,我尝试了很多东西而且没办法,总是出现这个错误,

我在快速框架中的服务器设置 -

var express = require('express');

var app = express()
    , fs = require('fs')
    , path = require('path');

var env = process.env.NODE_ENV || 'production'
    , config = require('./config/config')[env]
    , mongoose = require('mongoose');

var http = require('http');

var db = mongoose.connect('mongodb://localhost/orbitax');


app.use(express.static(__dirname + '/public'));


var bodyParser = require('body-parser'); // add body-parser for interact with server and client data


var jsonParser = bodyParser.json(); //join this body parser with json file

var urlencodedParser = bodyParser.urlencoded({ extended: false});


//Initialize Models
var models_path = __dirname + '/app/models'
fs.readdirSync(models_path).forEach(function (file) {

  require(models_path+'/'+file)
});

require('./config/routes')(app,config);

var server = app.listen(9000, function(){
    var host = server.address().address;
    var port = server.address().port;

});

服务器路由,

var async = require('async')
    , mongoose = require('mongoose')
    , uploadModel = mongoose.model('uploadModel');


module.exports = function (app) {


  // upload routes

  var upload = require('../app/controller/upload');

  app.get('/newUpload', upload.newUpload);

  app.post('/create_new_directory', upload.create_new_directory);


}



exports.create_new_directory = function(req, res)
{
    console.log("hello")
    console.log(req.body);
}

从客户端请求是,

$http({'method': 'post', 'url': '/create_new_directory', data: $scope.directory })
            .success(function(data){
                console.log(data)
            })
            .error(function(){

            })

任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:3)

默认情况下,def tearDown(self): User.objects.all().delete() 服务仅在数据是对象时才将请求数据转换为JSON字符串。

https://github.com/angular/angular.js/blob/v1.4.8/src/ng/http.js#L292

在您的情况下,请求数据是一个字符串,因此它不会被引号括起来,使其成为无效的JSON。

您应该可以像这样修改$http配置:

$http