2017-07-27 131 views
0

我一直有一个问题,整天通过ajax发送JSON数据到Express。 我的AJAX看起来是这样的:意外令牌U 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"); 
     } 

    }); 
}); 

和我的快递类的路线是这样的:

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' 
     }) 
    }); 


}); 

我发出了邮递员POST请求的URL与此JSON对象:

{ 
    "username":"testing", 
    "title":"123", 
    "description":"j456", 
    "text":"seven" 
} 

和Express记录了控制台中的所有细节,所以它必须是我的ajax请求的问题,因为它给了我一个意外的令牌u错误,但我不知道是什么原因造成的它。有任何想法吗?

+1

视图是用快速呈现吗?如果没有,你必须指定完整的URL int he ajax字段(即:localhost:PORT/classes/updateAssignment /)并允许cors。另外,你可以复制粘贴你正在得到的确切的错误? – ThomasK

+0

Thew views are express with express, 这是我得到的确切错误: SyntaxError:意外的令牌ü 在解析(L:\ CSSE \ SPUR2017 \ authentication \ node_modules \ body-parser \ lib \ types \ json .js:83:15)等。 – MrShedford

+1

好的,这是一个节点错误。解析器无法解析你的身体。阿贾克斯看起来很好。你有没有添加适当的json解析到你的中间件?在使用邮递员时,你发送了什么标题? – ThomasK

回答

2

尝试删除contentType: "application/json",

如果您使用的邮递员,没有头,很可能这是导致解析器失败。