Boyan Hristov
Boyan Hristov

Reputation: 1092

Using CORS on node.js server on a phonegap application

I am trying to connect my cordova/phonegap application with my node.js server. Problem is, I get this error "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. " . I tried adding this middleware to my node.js server, entering my phonegap domain, then, just for testing purpouses of course, I figured I will allow ALL domains for CORS, still no luck. This is what I used on my node.js server:

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

And I am doing a pretty simple AJAX request from my phonegap application, which I think is pretty much correct. I am getting this error on my phonegap app and on the node.js server console I get an error from one of the controllers, saying can't see property X of undefined, which undefined is my req.body. Here is the request:

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

Upvotes: 2

Views: 1657

Answers (1)

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

Allowing * origin access on your node server is a bad idea. http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html you can declare all domains to be supported by your app in phonegap itself, using element in cordova.xml. have a look at this Phonegap Cross-domain AJAX POST Request not working on Android

Edit

: From comment below: if you need to allow access to any origin from chrome just for development purpose there is a plugin https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

Upvotes: 2

Related Questions