【问题标题】:How to use Node.js without callback inside of jquery ajax request?如何在 jquery ajax 请求中使用没有回调的 Node.js?
【发布时间】:2016-12-25 19:15:28
【问题描述】:

我花了很多时间来了解为什么我的 Node.js 服务使用 postman 运行良好的原因。如果您看下面,您可以看到我的 node.js 服务运行良好。但是JQUERY代码(调用GetAllNotifyTypesFunc();)

给我错误:(如何在没有回调的情况下调用正确的邮递员和 jquery?)

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.writeHead(200, {
                //   'Content-Type': 'application/json'
                //    });
                // res.end('callback(\'' + JSON.stringify(result) + '\')');
                res.writeHead(200, {
                    'Content-Type': 'application/json'
                });
                res.end(JSON.stringify(result));
                // res.json(result);
            }
        })
    })
});

var port = Number(process.env.PORT || 5000);
app.listen(port, function () {
    console.log("Listening on " + port);
})

如果我使用邮递员:

    $(function () {

    GetAllNotifyTypesFunc();

});

var GetAllNotifyTypesFunc = function () {
    console.log("notify");

    $.ajax({
        url: 'http://127.0.0.1:5000/Notifies',
        dataType: "jsonp",
        async: false,
        //jsonpCallback: "callback",
        cache: false,
        timeout: 5000,
        success: function (data) {
            console.log(data);
            console.log(JSON.parse(data));
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('error ' + textStatus + " " + errorThrown);
        }
    });


}

【问题讨论】:

    标签: javascript jquery ajax node.js mongodb


    【解决方案1】:

    您说 jquery 响应将是 jsonp 但它是 json。您需要检查差异,我想您应该使用:

    dataType: "json",
    

    jsonp 是可执行函数,见 (What are the differences between JSON and JSONP?)

    【讨论】:

    • 跨域呢?没有jsonp,我能处理跨域吗?
    • jquery-2.0.3.min.js:6 XMLHttpRequest 无法加载 127.0.0.1:5000/Notifies?_=1482684143180。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin '127.0.0.1:13227' 不允许访问。发送@ jquery-2.0.3.min.js:6 Test.html:36 错误错误 NetworkError: 无法在 'XMLHttpRequest' 上执行 'send': 无法加载 '127.0.0.1:5000/Notifies?_=1482684143180'。
    • @Penguen - 你知道浏览器中有哪些跨域安全限制吗?您不能从当前页面域以外的站点请求 ajax 调用,除非该站点明确启用跨源请求。您可以搜索“node.js CORS”以了解如何在您的 node.js 服务器中启用跨源请求。 Postman 不像浏览器那样限制跨源请求。
    猜你喜欢
    • 2013-08-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 2011-06-05
    • 2011-07-19
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多