gpt4 book ai didi

javascript - 如何在 jquery ajax 请求内部不回调的情况下使用 Node.js?

转载 作者:行者123 更新时间:2023-12-03 05:22:22 26 4
gpt4 key购买 nike

我花了很多时间来理解为什么我的 Node.js 服务通过使用 postman 运行得很好。如果您看下面,您会发现我的 Node.js 服务运行良好。但是JQUERY代码(调用GetAllNotifyTypesFunc();)

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

enter image description here

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

如果我使用 postman :

enter image description here

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


}

最佳答案

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

dataType: "json",

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

关于javascript - 如何在 jquery ajax 请求内部不回调的情况下使用 Node.js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41320583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com