【发布时间】:2017-07-27 14:25:59
【问题描述】:
我整天都在通过 ajax 向 Express 发送 json 数据时遇到问题。 我的 ajax 看起来像这样:
$('#saveClause').click(function () {
var username = document.getElementById('postUserName').innerHTML;
var clauseTitle = document.getElementById('modalTitle').innerHTML;
var clauseDescription = document.getElementById('modalDescription').innerHTML;
var clauseText = document.getElementById('modalText').innerHTML;
$.ajax({
url: "/classes/updateAssignment",
type: "post",
dataType: "json",
data: {
username: username,
title: clauseTitle,
description: clauseDescription,
text: clauseText
},
cache: false,
contentType: "application/json",
complete: function () {
console.log("complete");
},
success: function () {
console.log("success");
},
error: function () {
console.log("Process Error");
}
});
});
我的 Express Classes 路线如下所示:
router.post('/updateAssignment', function (req, res) {
console.log(req.body.username)
console.log(req.body.title);
console.log(req.body.description);
console.log(req.body.text);
res.type('json');
res.send({
some: JSON.stringify({
response: 'json'
})
});
});
我向带有这个 JSON 对象的 url 发出了一个邮递员 post 请求:
{
"username":"testing",
"title":"123",
"description":"j456",
"text":"seven"
}
并且 Express 在控制台中记录了所有详细信息,所以这一定是我的 ajax 请求有问题,因为它给了我一个意外的令牌 u 错误,但我不知道是什么原因造成的。有什么想法吗?
【问题讨论】:
-
视图是用 express 渲染的吗?如果没有,您必须在 ajax 字段中指定完整的 url(即:localhost:PORT/classes/updateAssignment/)并允许 cors。另外,你能复制粘贴你得到的确切错误吗?
-
Thew 视图正在使用 express 呈现,这是我得到的确切错误: SyntaxError: Unexpected token u at parse (L:\CSSE\SPUR2017\authentication\node_modules\body-parser\lib \types\json.js:83:15) 等
-
好的,这是一个节点错误。解析器无法解析您的身体。 ajax 看起来不错。您是否将正确的 json 解析添加到中间件?使用邮递员时,您发送了哪些标头?
-
好的,然后尝试在 ajax 调用中去掉内容类型 json
-
介意我回答一下吗?我是这个社区的新手,我正在努力获得一些声誉:)
标签: javascript json ajax express