javascript - 平均堆栈 : "SyntaxError: Unexpected token f" Comments not posting

标签 javascript json node.js mean-stack

我正在开发一个博客,您可以在其中回答问题,人们可以对答案发表评论。提问和回答问题效果很好。但发表评论则不然。 经过调查我知道它与 JSON 相关。可能以某种方式处理主体解析器。也许我错了。花了几个小时比较代码,找不到错误所在。这是错误和 console.log:

POST http://localhost:8000/answers/5807c9ef24adc7ea591a35b1/comments/ 400 (Bad Request)

Object {data: "SyntaxError: Unexpected token f<br> &nbsp; &nbsp;a… &nbsp;at process._tickCallback (node.js:356:17)↵", status: 400, config: Object, statusText: "Bad Request"}
config
:
Object
data
:
"SyntaxError: Unexpected token f<br> &nbsp; &nbsp;at parse (C:\Users\US\Documents\coding\KelvinDashDemo\node_modules\body-parser\lib\types\json.js:83:15)<br> &nbsp; &nbsp;at C:\Users\US\Documents\coding\KelvinDashDemo\node_modules\body-parser\lib\read.js:116:18<br> &nbsp; &nbsp;at invokeCallback (C:\Users\US\Documents\coding\KelvinDashDemo\node_modules\body-parser\node_modules\raw-body\index.js:262:16)<br> &nbsp; &nbsp;at done (C:\Users\US\Documents\coding\KelvinDashDemo\node_modules\body-parser\node_modules\raw-body\index.js:251:7)<br> &nbsp; &nbsp;at IncomingMessage.onEnd (C:\Users\US\Documents\coding\KelvinDashDemo\node_modules\body-parser\node_modules\raw-body\index.js:307:7)<br> &nbsp; &nbsp;at emitNone (events.js:67:13)<br> &nbsp; &nbsp;at IncomingMessage.emit (events.js:166:7)<br> &nbsp; &nbsp;at endReadableNT (_stream_readable.js:921:12)<br> &nbsp; &nbsp;at nextTickCallbackWith2Args (node.js:442:9)<br> &nbsp; &nbsp;at process._tickCallback (node.js:356:17)↵"
headers
:
(d)
status
:
400
statusText
:
"Bad Request"
__proto__
:
Object

这是我的 app.js:

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var path = require('path');


//App init
var app = express();
require('./server/config/mongoose.js');

var sessionConfig = {
 secret:'CookieMonster', // Secret name for decoding secret and such
 resave:false, // Don't resave session if no changes were made
 saveUninitialized: true, // Don't save session if there was nothing initialized
 name:'myCookie', // Sets a custom cookie name
 cookie: {
  secure: false, // This need to be true, but only on HTTPS
  httpOnly:false, // Forces cookies to only be used over http
  maxAge: 3600000
 }
}

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({extended:true}));
app.use(expressSession(sessionConfig));

我的客户端commentFactory:

kelvindashdemo.factory('CommentFactory', ['$http', function($http){
	var factory = {};
	factory.createComment = function(comment, topicId, callback){
		$http({
			method:"POST",
			url:"/answers/"+topicId+"/comments/",
			data:comment
		}).then(function success(){
			callback();
		}, function failure(res){
			console.log(res);
		})	
	}
    factory.dislike = function(id,callback){
	$http({
		method:"GET",
		url:"/comments/dislike/"+id
	}).then(function success(){
		callback();
	}, function failure(res){
		console.log(res);
	})			
}
factory.like = function(id,callback){
	$http({
		method:"GET",
		url:"/comments/like/"+id
	}).then(function success(){
		callback();
	}, function failure(res){
		console.log(res);
	})			
}
return factory;
}]);

我的服务器端commentController:

var mongoose = require('mongoose');
var Answer = mongoose.model('Answer');
var User = mongoose.model('User');
var Comment = mongoose.model('Comment');

module.exports = {
	createNew: function(req, res){
		console.log("HERE");
		var commentInfo = req.body;
		commentInfo._author = req.session.user;
		commentInfo._answer = req.params.id;
		var comment = new Comment(commentInfo);
		comment.save(function(err, comment){
			User.update({_id:req.session.user}, {$push:{comments:comment}}, function(err, user){		//pushes comment into user db with id
				Answer.update({_id:req.params.id}, {$push:{comments:comment}}, function(err, comment){	//pushes comment into topic db with id
					if (!err){
						res.sendStatus(200);
					}else{
						res.sendStatus(400);			//can also be a 500 error msg
					}
				});
			});
		})
	},

最后是我的服务器端评论模型:

var mongoose = require('mongoose');

var CommentSchema = new mongoose.Schema({
	comment: {type:String, required:true},	
	_answer: {type: mongoose.Schema.Types.ObjectId, required:true, ref: 'Answer'},
	likes: {type:Number, default:0},
	dislikes: {type:Number, default:0},
	_author: {type: mongoose.Schema.Types.ObjectId, required:true, ref: 'User'},
}, {timestamps:true});

mongoose.model('Comment', CommentSchema);
添加到我的 topicController 中以供引用:

kelvindashdemo.controller('topicsController', ['$scope', 'TopicFactory', '$location', '$routeParams', 'AnswerFactory', 'CommentFactory', function($scope, TopicFactory, $location, $routeParams, AnswerFactory, CommentFactory){
	TopicFactory.getTopic($routeParams.id, function(topic){		
		$scope.topic = topic;
		console.log(topic);
	})
	$scope.postAnswer = function(answer, topicId){						AnswerFactory.createAnswer(answer, topicId, function(){				TopicFactory.getTopic($routeParams.id, function(topic){		
				$scope.topic = topic;
				$scope.answer = {};
				console.log(topic);
			})
		})
	}
	$scope.postComment = function(comment, answerId){			
		CommentFactory.createComment(Comment, answerId, function(){			
			TopicFactory.getTopic($routeParams.id, function(topic){			
				$scope.topic = topic;
				console.log(topic);			
			})
		})
	}
	$scope.like = function(id){
		CommentFactory.like(id, function(){			
			TopicFactory.getTopic($routeParams.id, function(topic){		
				$scope.topic = topic;
				console.log(topic);
			})
		})
	}
	$scope.dislike = function(id){
		CommentFactory.dislike(id, function(){			
			TopicFactory.getTopic($routeParams.id, function(topic){		
				$scope.topic = topic;
				console.log(topic);
			})
		})
	}
}])

欢迎任何和所有反馈。我期待在某个地方听到它缺少逗号。

最佳答案

当您调用createComment时:

$scope.postComment = function(comment, answerId) {
  CommentFactory.createComment(Comment, answerId, function(){           
    TopicFactory.getTopic($routeParams.id, function(topic){         
      $scope.topic = topic;
      console.log(topic);           
    })
  })
}

...您正在传递 Comment,它在您发布的任何代码中都没有定义,但我猜测它是某种构造函数。在该函数中:

factory.createComment = function(comment, topicId, callback){
    $http({
        method:"POST",
        url:"/answers/"+topicId+"/comments/",
        data:comment
    }).then(function success(){
        callback();
    }, function failure(res){
        console.log(res);
    })  
}

...第一个参数作为数据发送到$http。如果 Comment 是一个函数,而不是可以序列化为 JSON 的对象,它会被转换为字符串 function Comment() {[native code]},这将炸毁服务器上的 JSON 解析器(注意它提示遇到 f 字符)。

认为你的意思是在调用CommentFactory.createComment时传递comment,而不是Comment :

$scope.postComment = function(comment, answerId) {
  CommentFactory.createComment(comment, answerId, function(){           
    TopicFactory.getTopic($routeParams.id, function(topic){         
      $scope.topic = topic;
      console.log(topic);           
    })
  })
}

关于javascript - 平均堆栈 : "SyntaxError: Unexpected token f" Comments not posting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40164851/

相关文章:

javascript - HTML 页面重新加载 - 模拟 CTRL+F5

ios - Swift iOS Twitter API 失败

python - 在 Python 中扁平化/反规范化 Dict/Json

javascript - 可以将 math.max 用于对象数组吗?

javascript - 使用 Gulp 删除所有有异常的文件

node.js - Node JS : How to create custom variables?

Javascript, jquery 错误 TypeError : $(. ..).autocomplete is not a function

javascript - 在javascript中读取sql查询输出

java - 如何将逗号和分号分隔的字符串拆分为 JSON 对象

javascript - TypeOf 上不存在属性,更好地理解类