Patrik18
Patrik18

Reputation: 329

Not allowed by Access-Control-Allow-Origin issue

I'm rtying to POST some data from client-side to server-side's script and I still got this Eroor:

OPTIONS http://localhost/site/dbs.js Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin. jquery.js:9597
XMLHttpRequest cannot load http://localhost/site/dbs.js. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.

server.js is runing no node.js (path /wamp/www/site/server.js)

var app = require('express')();
var server = require('http').createServer(app);
var mysql = require('mysql');
var port = process.env.PORT || 8080;
server.listen(port);

app.get('/', function(req, res){
  res.sendfile(__dirname + '/index.html');
});

app.get('/dbs.js', function(req, res) {
  res.sendfile(__dirname + '/dbs.js');
});

in index.html with ajax() I call to post some data to dbs.js:

$.ajax({
        type: "POST",
        url: " http://localhost:80/site/dbs.js",
        data: "name="+username+"&pwd="password,
        succes: function(ret)
        {
          if(ret==0)
            ;
        }
      });

dbs.js:

var name;
var pwd;
function DbConn()
{
            var mydb = mysql.createConnection({
              host: 'localhost',
              user: 'root',
              password: 'admin123',
              database: 'users'
            });

            mydb.connect();

            var query = ('select passwd from peer where username=' + username);

            console.log(query);

            connection.end(function(err) {
              // The connection is terminated now
            });
}

If I change somethig in URL, I got an Error: 404 - Not found "dbs.js" All source is in one folder(wamp/www/site/). Do you think it will be necessary add some XML header in dbs.js

Upvotes: 0

Views: 11764

Answers (2)

jaycruz805
jaycruz805

Reputation: 1

I had to battle with this error for a while, but finally conquered it. I was getting this error because I was trying to create a SocketIO connection across different domains. Did some research and turns out browsers don't like making any cross domain requests (ajax,sockets ...) within the rending html page. Turns out the server (the one we are making the illegal request to) has to allow this functionality.

In your case try an express middleware before all your routes:

//Gloabal middleware
app.get('/*',function(request,response,next){
  response.header('Access-Control-Allow-Origin' , 'http://domain' );
  response.header('Access-Control-Allow-Credentials', true);
  next();
});

Upvotes: 0

Roemer
Roemer

Reputation: 3576

There is a common problem with localhost, ajax calls (and chrome) which result in the error you have. Please take a look at the related question, especially this one: Origin http://localhost is not allowed by Access-Control-Allow-Origin

Upvotes: 2

Related Questions