【问题标题】:How to call Node.js service inside jquery script?如何在 jquery 脚本中调用 Node.js 服务?
【发布时间】: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


【解决方案1】:

由于生成了“parseerror”,我认为获取的数据不是正确的 JSON 格式。
尝试在 NodeJS 代码中使用 res.json 而不是 res.send
如果不起作用,请使用 HTTP 客户端等 POSTman 并检查“/Notifies”的响应。您将能够像这样使用JSON parser 来检查响应是否采用正确的 JSON 格式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    相关资源
    最近更新 更多