Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST AJAX request denied - CORS?

I have setup CORS on my node.js server on port 5000 as follows:

var app = express();

app.use(cors()); //normal CORS
app.options('*', cors()); //preflight 

app.post('/connect', function(req, res) { 
    console.log("Connection request received !")
});

var port = 5000;
app.listen(port, function () {
    console.log('Listening on port '+port);
});

I am now trying to send AJAX POST requests using JQuery like so, in a static web page open from my hard disk :

var xhr = $.post({
            url: 'http://localhost:5000/connect',
            complete: function() {
                console.log("done !")
            },
            crossDomain: true
        });

xhr.fail(function(xhr, status, error){
    alert(error)
})

The complete function is never called, and the only alert I get is an alert from the XHR fail handler, containing the following error :

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied

I think CORS is well-configured, what am I missing ?


EDIT : for those in my case, the best solution I could find was to send the page from the server :

app.use(express.static('web'))

app.get("/", function(req, res) {
    res.sendFile(__dirname + '/web/HTML/index.html');
});
like image 992
Magix Avatar asked Sep 07 '16 07:09

Magix


People also ask

How to fix CORS issue in ajax call?

Re: CORS issue after ajax post requestYour server needs to not only allow POSTs from the origin using Access-Control-Allow-Origin (origin = your Marketo LP domain including protocol, like https://pages.example.com), it also needs to allow the Content-Type header using Access-Control-Allow-Headers.

How do I get a cross origin resource sharing CORS POST request to work?

The CORS mechanism works by adding HTTP headers to cross-domain HTTP requests and responses. These headers indicate the origin of the request and the server must indicate via headers in the response whether it will serve resources to this origin. This exchange of headers is what makes CORS a secure mechanism.

What is Crossdomain in ajax?

For a successful cross-domain communication, we need to use dataType “jsonp” in jquery ajax call. JSONP or “JSON with padding” is a complement to the base JSON data format which provides a method to request data from a server in a different domain, something prohibited by typical web browsers.


2 Answers

This is the code I am using. It is located in my app.js file

app.all("/*", function (req, res, next) {

  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Credentials",true);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type,Accept,X-Access-Token,X-Key,Authorization,X-Requested-With,Origin,Access-Control-Allow-Origin,Access-Control-Allow-Credentials');
  if (req.method === 'OPTIONS') {
    res.status(200).end();
  } else {
    next();
  }
});
like image 152
frikkievb Avatar answered Sep 19 '22 17:09

frikkievb


I've never used cors() so I can't speak to that piece. But you could manually allow cross origin resource sharing by setting up the node.js headers.

Add This Pre-Route on All Requests

app.route('*')
   .all(function(req, res, next) {
     res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
     res.header('Access-Control-Allow-Origin', '*');
     res.header('Access-Control-Allow-Headers', 'X-API-TOKEN, Content-Type, Authorization, Content-Length, X-Requested-Wit
h');
   next();
})

This should work.

like image 28
Timothy Moody Avatar answered Sep 20 '22 17:09

Timothy Moody