Javascript AJAX SyntaxError:意外的令牌E在JSON位置0在ajax + node.js
我正在做一个AJAX POST请求与多个对象到一个node.js服务器。虽然我的服务器发送状态码200
,但我仍然收到错误Javascript AJAX SyntaxError: Unexpected token E in JSON at position 0
。这里是我的POST请求:Javascript AJAX SyntaxError:意外的令牌E在JSON位置0在ajax + node.js
var company_id = "some_generic_id";
var president = "obama";
var postData = {
company_id : company_id,
president : president
};
$.ajax({
type: "POST",
url: '/api/test_link',
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
data: postData,
success: function(data, status) {
console.log('it worked!')
},
error: function(request, status, error) {
console.log(request);
console.log(status);
console.log(error);
}
});
,这里是我的服务器端代码:
app.post('/api/test_link', function(req, res) {
console.log('--post data--');
console.log(req.body);
/*
prints out:
--post data--
{ company_id: 'company_id', president: 'obama' }
*/
res.sendStatus(200);
});
下面是从我的网络选项卡上的图像:
有谁知道我可能会丢失或为什么我的postData
语法无效?
The docs Ajax的呼叫状态有关dataType
选项:
The type of data that you're expecting back from the server. "json": Evaluates the response as JSON and returns a JavaScript object.
既然你不返回从服务器上的任何数据,你空的数据解析为JSON,产生的误差。如果您没有返回任何数据,只需删除dataType: "json"
即可。
在app.post('/api/test_link', function(req, res) {
开头添加res.writeHead(200, {"Content-Type": "application/json"});
指定您希望响应为JSON格式
删除您
res.sendStatus(200);
由于res.writeHead(200, {'Content-Type': 'application/json'});
也将设置你的StatusCode
因此,这将是这个样子
app.post('/api/test_link', function(req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
console.log('--post data--');
console.log(req.body);
/*
prints out:
--post data--
{ company_id: 'company_id', president: 'obama' }
*/
res.send();
});
嗨 - 我试过'res.send({status:200})'这似乎工作......请给我一个例子,我应该添加'res.writeHead(200,{ “Content-Type”:“application/json”});'? –
他指定'dataType:“json”',所以响应将被解析为JSON而不管返回的MIME类型 –
检查您的网络响应看到它的结果? – Beginner
我的网络响应是一个状态200 ..但由于它返回200,这是不是说AJAX请求成功(而不是错误)? –
它在你的网络响应中显示json对象吗?检查 – Beginner