javascript - 在phonegap应用程序的node.js服务器上使用CORS

标签 javascript ajax node.js cordova cors

我正在尝试将我的 cordova/phonegap 应用程序与我的 node.js 服务器连接。问题是,我收到此错误 “XMLHttpRequest 无法加载 http://127.0.0.1:1234/api/users。请求的资源上不存在“Access-Control-Allow-Origin” header 。Origin 'http://localhost:5000' 因此不允许访问。响应的 HTTP 状态代码为 500。 " 。我尝试将此中间件添加到我的node.js服务器,输入我的phonegap域,然后,当然,只是出于测试目的,我想我将允许CORS的所有域,但仍然没有运气。这是我在 Node.js 服务器上使用的:

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware

    next();
});

我正在从我的phonegap应用程序执行一个非常简单的AJAX请求,我认为这是非常正确的。我在我的phonegap应用程序上收到此错误,在node.js服务器控制台上,我从其中一个 Controller 收到错误,说看不到未定义的属性X,其中未定义是我的req.body。这是请求:

var serverURL = 'http://127.0.0.1:1234';
    var body = {

        userId : '123A',
        comment: {
            from: '123B',
            content: 'I am a new generation of 123! :)'
        }
    };
    var bodyToString = JSON.stringify(body);


    $.ajax({url: serverURL + "/api/plates", dataType: "json", type: "PUT", data: bodyToString}).done(function (data) {
        alert(data);
    });

最佳答案

允许 * 在 Node 服务器上进行原始访问是一个坏主意。 http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html您可以使用 cordova.xml 中的元素在 PhoneGap 本身中声明您的应用程序支持的所有域。看看这个Phonegap Cross-domain AJAX POST Request not working on Android

Edit

: 来自下面的评论:如果您需要允许从 chrome 访问任何来源只是出于开发目的,那么有一个插件 https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

关于javascript - 在phonegap应用程序的node.js服务器上使用CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26399348/

相关文章:

javascript - React Native setState JSON 对象

javascript - 允许 angularjs 中的字母数字指令使用破折号

javascript - 使用 jQuery 从 COMBO BOX 中获取选定的值

jquery - 如果 ajax 在一段时间后没有成功,我该如何取消它并执行操作?

javascript - Python 的 %s 等同于 Javascript?

javascript - 使用多个版本号的多个 Maven 依赖项

javascript - 使用 JavaScript 裁剪图像

php - jQuery和AJAX上的错误报告

javascript - Discord.js - 让用户上次事件?

node.js - 在 Mongoose 中保存填充值