我正在尝试从客户端POST一些数据到服务器端脚本,我仍然得到这个页面:
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 running 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');
});
在index.html与ajax()我调用张贴一些数据到db .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 -没有找到"dbs.js"所有的源代码都在一个文件夹(wamp/www/site/)。你认为有必要在db .js
有一个常见的问题与localhost, ajax调用(和chrome),导致你的错误。请看相关的问题,尤其是这个:Access-Control-Allow-Origin
我不得不与这个错误作斗争一段时间,但最终克服了它。我得到这个错误,因为我试图创建跨不同域的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();
});