【发布时间】:2016-12-24 21:09:50
【问题描述】:
我是 .net 开发人员。我决定通过使用示例来学习 Node.js。我创建了一个 node.js 服务来从 Mongo db 数据库中收集数据。然后我有一个 HTML 网页。我使用了一个简单的 jquery 代码来获取这个 node.js 网络服务。但是我遇到了这个错误:请求的 JSON 解析失败。
我的数据库:
{ "_id" : ObjectId("58568264477db6913051a0cf"), “名称”:“优素福” }
{ "_id" : ObjectId("58568381477db6913051a0d0"), “名称”:“莱拉” }
我的服务器代码:(Node.js)
'use strict';
var express = require("express");
var app = express();
var MongoClient = require('mongodb').MongoClient;
var router = express.Router();
app.get('/Notifies', function (req, res) {
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
coll.find({}).toArray(function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
})
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function () {
console.log("Listening on " + port);
})
Jquery:
var GetAllNotifyTypesFunc = function () {
console.log("notify");
$.ajax({
url: 'http://127.0.0.1:5000/Notifies',
type: 'GET',
dataType: 'jsonp',
async: false,
contentType: 'application/json; charset=utf-8',
success: function (data) {
var str = '';
console.log(data);
$.each(data, function (idx, elem) {
console.log(elem.Name);
str += "\"" + elem.Name + "\"" + " : " + "{ \"!type\": \"bool\" }" + ",";
});
str = str.substring(0, str.length - 1);;
str = "{" + str + "}";
localStorage.removeItem("alarms");
localStorage.setItem('alarms', str);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
上面的代码返回给我这个错误:Requested JSON parse failed.
【问题讨论】:
-
1.为什么使用
jsonp作为 Accept 标头?如果您说“好的,响应将是application/jsonp您必须提供回调来解码响应。记住,json != jsonp。2. 如果您的服务在另一个域中,只需启用 CORS在您的客户端域的服务器上并将dataType设置为json。有关更多信息:Request JSON parse failed发生是因为您没有为 JSONP 响应指定回调。
标签: javascript jquery json node.js mongodb