Ajax查询响应成功,但会引发错误

时间:2018-12-27 16:52:03

标签: javascript ajax mongodb express body-parser

我是mongodb的新手,正在使用 Express Body-Parser Mongoose ,并且我有一个mongodb数据库(在线,它的调用mlab)我从中提取数据的地方。一切正常,我已经使用邮差来获取,发布和删除。我试图获取JavaScript中的数据,以便可以在html中显示。我正在使用Ajax,它可以工作并返回成功,但是会触发Ajax的fail功能。

mongdb控制器

exports.photoalbum_all = function (req, res, next) {
PhotoAlbum.find(({}), function (err, photoalbum) {
    if (err) return next(err);
    res.send("../Views/images", {photo: photoalbum});
});};

我正在拨打Ajax电话

                    function getPhoto() {
                        var photoAdd = 'http://localhost:1234/photoalbums/find'; 
                        $.ajax({
                            header: 'Access-Control-Allow-Origin: *',
                            dataType: "jsonp",
                            url: photoAdd,
                            contentType: 'application/json; charset=utf-8',
                            async: false,
                            crossDomain: true,
                            success: AjaxSucceeded,//callback,
                            error: AjaxFailed
                        });
                    }
                    function AjaxSucceeded(result) {
                        alert("hello");
                        alert(result);
                    }
                    function AjaxFailed(result) {
                        debugger;
                        alert("hello1");
                        alert(result.statusText);
                    }
                    getPhoto();

起初,我遇到有关 ajax跨域请求被阻止的错误,因此我不得不使用数据类型:'jsonp'。 就像我说的那样,当我在chrome浏览器控制台的网络中签入时,我得到了成功和以下地址:

http://localhost:1234/photoalbums/find?callback=jQuery111202567313069615542_1545928466705&_=1545928466706

返回此Json值

[{"_id":"5c22a5ffcb29611f905f756b","title":"prayer","albums":[{"_id":"5c22a5ffcb29611f905f756c","u_name":"family01","u_title":"family_man"}],"createdAt":"2018-12-25T21:49:51.091Z","updatedAt":"2018-12-25T21:49:51.091Z","__v":0},{"_id":"5c22a66bd3527c39342fafe7","title":"prayer","albums":[{"_id":"5c22a66bd3527c39342fafe8","u_name":"family01","u_title":"family_man"}],"createdAt":"2018-12-25T21:51:39.274Z","updatedAt":"2018-12-25T21:51:39.274Z","__v":0}]

我已经竭尽全力地进行研究,但是毫无疑问,我很怀疑,我从mlab得到的Json响应是否可能是问题,我的意思是格式化。我愿意接受任何想法。感谢您的提前帮助。

1 个答案:

答案 0 :(得分:0)

除了JSONP,在客户端没有其他事情要做。如果要对服务器使用正确的Ajax JSON调用,则需要在本地主机上启用CORS。

这里有一些有关如何Deadly CORS when http://localhost is the origin的教程

您也可以在Google上搜索它:在本地主机上启用CORS

希望这会有所帮助