cometd / cometd-nodejs-server

CometD server for NodeJS
Apache License 2.0
12 stars 4 forks source link

Getting No 'Access-Control-Allow-Origin' header is present on the requested resource. #10

Closed alberdg closed 6 years ago

alberdg commented 6 years ago

Hi,

I am unsuccessfully trying to connect to my cometd server and getting: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I read the javascript cometd documentation at but does not provide much detail for javascript.

I have added the following configuration but still the same

cometd.createCometDServer({
        logLevel: 'info', // Emits logging on the console
        timeout: 10000, // Heartbeat timeout in milliseconds
        maxInterval: 15000,
        requestHeaders:{
          'Access-Control-Allow-Origin': 'http://localhost:19002'
        }
      })

Could you please provide some help with this?

Thanks!

sbordet commented 6 years ago

You are making a cross origin request to your CometD server, so you need CORS.

There exist a NPM cors package to be used with Express.

The Access-Control-Allow-Origin is a header that should be added to the response.

If you're going to do CORS manually, I recommend that you do it separately from CometD, as a wrapper function that is invoked before CometD, for example:

var http = require('http');
var cometd = require('cometd-nodejs-server');
var cometdServer = cometd.createCometDServer();
var cors = function(request, response) {
    // First CORS handling.
    // Then forward to cometdServer.handle(request, response).
}
var httpServer = http.createServer(cors);

Let know if that worked for you.

alberdg commented 6 years ago

Hi Simone,

Thanks for the prompt answer, it worked perfectly!!

Thanks!

sbordet commented 6 years ago

What did you use, NPM cors or the wrapper ? Feel free to close the issue if it's solved for you.

alberdg commented 6 years ago

I used the wrapper

this.cometdHttpServer = http.createServer((req, res) => {
        res.setHeader('Access-Control-Allow-Origin', '*')
        res.setHeader('Access-Control-Allow-Headers', 'x-requested-with,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Pragma,Cache-Control')
        this.cometd.handle(req, res)
      })

That code did the trick so I'm closing it.

Thanks!

sbordet commented 6 years ago

Remember that there is a security reason for CORS and that allowing all origins may not be desirable.

alberdg commented 6 years ago

Yes, that was just my first test!

Thanks for the reminder