简体   繁体   English

如何在Node.js中使用没有回调的jquery ajax请求?

[英]How to use Node.js without callback inside of jquery ajax request?

I have been passing lots of time to understand the reason Why my Node.js service is working very well by using postman. 我已经花了很多时间来了解为什么我的Node.js服务通过使用邮递员才能很好地工作的原因。 If you look below you can see my node.js service is working perfect. 如果您在下面看,您可以看到我的node.js服务运行正常。 But JQUERY code (calling GetAllNotifyTypesFunc();) 但是JQUERY代码(调用GetAllNotifyTypesFunc();)

Gives me error: (how to call correct both postman and jquery without callbacks?) 给我错误:(如何在没有回调的情况下调用正确的postman和jquery?)

在此处输入图片说明

Node.js : 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);
})

if I use Postman: 如果我使用邮递员:

在此处输入图片说明

    $(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);
        }
    });


}

You say jquery that response will be jsonp but it is json. 您说jquery响应将是jsonp但它是json。 You need to check the difference, i suppose that you should use: 您需要检查差异,我想您应该使用:

dataType: "json",

jsonp is fo executable functions, see ( What are the differences between JSON and JSONP? ) jsonp是可执行函数,请参阅( JSON和JSONP有什么区别?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM