在phonegap应用程序的node.js服务器上使用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域,然后,当然,只是为了testingpurpouses,我想我会允许所有域的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 (eg 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是我的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); }); 

允许在您的节点服务器上访问* origin是一个坏主意。 http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html你可以使用cordova.xml中的元素声明你的应用程序在phonegap中支持的所有域。 看看这个Phonegap的跨域AJAX POST请求不适用于Android

编辑

:从下面的评论:如果你需要允许访问来自铬的任何来源仅用于开发目的有一个插件https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi