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

时间:2014-10-16 08:13:23

标签: javascript ajax node.js cordova cors

我正在尝试将我的cordova / phonegap应用程序与我的node.js服务器连接。问题是,我收到此错误"XMLHttpRequest cannot load http://127.0.0.1:1234/api/users. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. The response had HTTP status code 500. "。我尝试将这个中间件添加到我的node.js服务器,进入我的phonegap域,然后,当然,只是为了测试purpouses,我想我将允许所有域为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服务器控制台上收到此错误我从其中一个控制器收到错误,说不能看到未定义的属性X,undefined是我的{{1} }}。这是请求:

req.body

1 个答案:

答案 0 :(得分:2)

在节点服务器上允许* origin访问是一个坏主意。 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

  

修改

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