I am .net developer. I decided to learn Node.js by using a sample. I created a node.js service to collect data from Mongo db database. And Then I have a HTML webpage . I used a simple jquery code to get this node.js web service. But I hot this error : Requested JSON parse failed.
My Db :
{ "_id" : ObjectId("58568264477db6913051a0cf"), "Name" : "yusuf" }
{ "_id" : ObjectId("58568381477db6913051a0d0"), "Name" : "leyla" }
My Server Code: (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);
}
This above code return to me this error: Requested JSON parse failed.
Since 'parseerror' is generated I think data is fetched by not in correct JSON format.
Try using res.json
instead of res.send
in NodeJS code
If not working use POSTman like HTTP client and check response for '/Notifies'. You will be able to use JSON parser like this to check whether response is in correct JSON format.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.