【问题标题】:Not allowed by Access-Control-Allow-Origin issueAccess-Control-Allow-Origin 问题不允许
【发布时间】:2016-04-12 03:16:59
【问题描述】:

我正在将一些数据从客户端发布到服务器端的脚本,但我仍然得到这个 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 没有运行 node.js(路径 /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');
});

index.htmlajax() 中我调用将一些数据发布到 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
            });
}

如果我更改 URL 中的某些内容,我会收到错误:404 - Not found "dbs.js" 所有来源都在一个文件夹中(wamp/www/site/)。 您认为有必要在 dbs.js 中添加一些 XML 标头

【问题讨论】:

标签: node.js cross-domain wamp


【解决方案1】:

localhost、ajax 调用(和 chrome)存在一个常见问题,导致您遇到错误。请看一下相关问题,尤其是这个问题:Origin http://localhost is not allowed by Access-Control-Allow-Origin

【讨论】:

    【解决方案2】:

    我不得不与这个错误作斗争一段时间,但最终克服了它。我收到此错误是因为我试图创建跨不同域的 SocketIO 连接。做了一些研究,结果发现浏览器不喜欢在渲染的 html 页面中发出任何跨域请求(ajax、sockets ...)。原来服务器(我们向其发出非法请求的服务器)必须允许此功能。

    在你的情况下,在你的所有路由之前尝试一个快速中间件:

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

    【讨论】:

    • 我刚刚看到你的 ajax 调用,调用端口 80。但是在你的 server.js 中,你可能在端口 8080 下注册它。你应该仔细检查你的服务器正在侦听的端口并正确相应地你的ajax。
    猜你喜欢
    • 2015-06-17
    • 2013-09-09
    • 2012-03-08
    • 2012-06-07
    • 2011-11-05
    相关资源
    最近更新 更多