CORS on node subdomain

Posted

技术标签:

【中文标题】CORS on node subdomain【英文标题】: 【发布时间】:2013-05-08 20:58:38 【问题描述】:

我正在尝试在子域上设置 API,因此我还尝试在 Web API 之后设置 javascript API。

但不幸的是,我在尝试通过 XMLHttpRequest() 访问服务器后遇到错误。

我一直在尝试使用我发现的几乎所有允许 CORS 的方式设置子域快速服务器,但仍然出现相同的错误。

更新

这里是文件:

app.js

    var express = require('express'),
    http = require('http'),
    path = require('path'),
    fs = require('fs'),
    app = express();

app.configure(function()
    app.set('port', process.env.PORT || 8080);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.cookieParser('S5crET!'));
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(express.vhost('localhost', require('./server/main.js').app));
    app.use(express.vhost('api.localhost', require('./server/api.js').app));
);

http.createServer(app).listen(app.get('port'), function()
  console.log('Express server listening on http://localhost:' + app.get('port'));
);

api.js

var express = require('express'),
    fs = require('fs'),
    check = require('validator').check,
    sanitize = require('validator').sanitize,
    mongojs = require('mongojs'),
    db = mongojs('mycity', ['user', 'reset', 'ranking', 'entries']),
    tool = require('../util/tool.js'),
    app = express();

app.options('/login', function (req, res)
    var uname, password;
    res.header("Access-Control-Allow-Origin", "*");
    //Escape user input and store in variables
    if (req.body.inputUserName) 
        uname = sanitize(req.body.inputUserName).xss();
        uname = sanitize(uname).escape();
     else  
        res.send(400, "state": false, "reason": "username not set");
        return; 
    
    //Escape password
    if (req.body.inputPassword) 
        password = sanitize(req.body.inputPassword).xss();
        password = sanitize(password).escape();
     else  
        res.send(400, "state": false, "reason": "password not set"); 
        return;

    //Search user with given username
    db.user.findOne('username': uname, function(err, data)
        //Error during db search
        if (err) res.send(400, "state": false, "reason": "Internal server error");
        else 
            //Check if there is a response otherwise username not found
            if (data) 
                //Check if user is blocked
                if (data.blocked ? data.blocked : false) 
                    res.send(200, "state": false, "reason": "You are blocked from the system");
                 else 
                    //Checks if password is the same like in the db
                    if (data.password == password) 
                        //Creating content of token
                        var atoken = tool.randomString(25);
                        //Checking if acccess token should be for 7 days or just a session token
                        /* Not really needed in the API
                        if (req.body.inputCheckbox)    
                            //send cookie that lasts 7 days to user
                            res.cookie('token', atoken, expires: new Date(Date.now() + 604800000) , httpOnly: true, signed: true);
                         else 
                            //send session cookie to user
                            res.cookie('token', atoken, maxage: null, httpOnly: true, signed: true);
                        
                        */
                        //Redirection to /
                        //res.redirect("/");
                        res.send(200, "state": true, "atoken": atoken, "id": data._id);
                        //set user online, save his ip ,date of last login and token in db
                        db.user.update('username': uname,  $set:  atoken: atoken, online: true, ip: req.ip, date: new Date(), attempt: 0);
                     else 
                        //Get current attempts of login with false password
                        var attempt = data.attempt ? data.attempt : 0;
                        //if attempts are more than equals 5 the user gets blocked 
                        if (attempt >= 5) 
                            res.send(200, "blocked");
                            //set user as blocked
                            db.user.update('username': uname, $set: blocked: true);
                            return
                        
                        //save attempts in db
                        db.user.update('username': uname,  $set:  'attempt': ++attempt);
                    
                
             else 
                //No such username found in db
                res.send(200, "state": false, "reason": "No such username in the system");
            
        
    );

  //res.render('index',  title: 'Express' );
);
app.post('/signup', function (req, res)
    //Escape user input
    var name = req.body.inputName ? sanitize(req.body.inputName).xss() : false;
        name = sanitize(name).escape();
    var email = req.body.inputEmail ? sanitize(req.body.inputEmail).xss() : false;
        email = sanitize(email).escape();
    var password = req.body.inputPassword ? sanitize(req.body.inputPassword).xss() : false;
        password = sanitize(password).escape();
    var password2 = req.body.inputPassword2 ? sanitize(req.body.inputPassword2).xss() : false;
        password2 = sanitize(password2).escape();

    //Check if userinput is set
    if (!name) res.send('name empty');return
    if (!email) res.send('email empty');return
    if (!password) res.send('password empty');return
    if (!password2) res.send('password2 empty');return
    if (password != password2) res.send('check pass');return

    //Save user data into db
    db.user.save(username: name, email: email, password: password, confirmed: false, function(err, data)
        if (err) res.send(500, false);
        if (data) 
            res.send(200, true);
            //send email to user for confirmation of email
         else res.send(200, false);
    );
);
app.post('/forgot', function (req, res)
    if (req.body.inputEmail) 
    //Escape user input
    var email = sanitize(req.body.inputEmail).xss();
        email = sanitize(email).escape();

    //Search after email in db
    db.user.findOne('email': email, function (err, data)
        if (err)  res.send(500, "Error"); return
        //If email found
        if (data) 
            //Random token will be created - uid ( User IDentification)
            var rand = tool.randomString(20);
            //Save the request in the DB
            db.reset.save('email': email, 'uid': rand, 'Date': new Date(), function (err, data)
                if (err)  res.send(500, "Error"); return 
                if (data) 
                    res.send(200, true);
                    //send email to given email with link to reset with the uid
                 else 
                    //In case of empty data
                    res.send(200, false);
                
            );
         else 
            // Response if mali not found
            res.send(200, 'No such email in system');
        
    );
     else 
        //Else if user input email is not set
        res.send(200, false);
    
);
app.get('/reset/:uid?', function (req, res)
    var uid;
    //Escape user input uid
    if(req.params.uid)
        uid = sanitize(req.params.uid).xss();
        uid = sanitize(uid).escape();
     else 
        res.send(200, 'uid empty');
        return
    

    //Search after uid in db
    db.reset.findOne(uid: uid, function (err, data)
        if (err)  res.send(200, "Error"); return ;
        //If uid found in db
        if (data) 
            res.send(200, true);
            //TODO: reset page
            //Remove uid from db: 
                //db.reset.remove(uid: uid);
         
        //If uid not found in db
        else 
            res.send(200, false);
        
    );
);
app.get('/ranking/:limit?', function (req, res)
    var limit = req.params.limit ? parseInt(req.params.limit) : 5;

    console.log(limit);

    db.ranking.find(null, _id: 0).limit(limit).sort("points": -1, function (err, data)
        if (err)  res.send(500, "Error"); return
        if (data) 
            res.send(200, data);
         else 
            res.send(200, "ERROR");
        
    );
);
app.get('/myCleanAPI.js', function (req, res)
    fs.readFile(__dirname.concat('/../api/myCleanAPI.js'), function (err, data)
        if (err)  res.send(500, "//Internal server error"); console.log(err); return
        if (data) 
            res.contentType('text/javascript');
            res.send(200, data);
        
    );
);
app.get('/', function (req, res)
    //console.log("API called");
    //res.send(200, "ttt");
    fs.readFile(__dirname.concat('/../api/index.html'), function (err, data)
        if (err)  res.send(500, "//Internal server error"); console.log(err); return
        if (data) 
            res.contentType('text/html');
            res.send(200, data);
        
    );
);

console.log('API is running');

exports.app = app;

ma​​in.js

var express = require("express"),
    path = require('path'),
    app = express();

app.configure(function()
    app.set('views', __dirname + '/../views');
    app.set('view engine', 'jade');
    app.use(express.cookieParser('S5cr5t!'));
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
);

app.get('/', function (req, res)
    res.render('index',  title: 'Express' );
);
app.get('/users', function (req, res)
  res.send("respond with a resource");
);

console.log("Main server running");

exports.app = app;

【问题讨论】:

我猜你的问题是“为什么我会收到错误”?在那种情况下,我们永远不会知道。您需要发布一些代码或展示您尝试过的内容,并说明它不起作用的场景 我们通过在我们的子域上有一个 api 并在我们的主站点上使用相同的路由在我们的单页应用程序中使用来避免这个问题。 AndyD:你能详细解释一下吗? Ian:对不起,我忘了添加它们。 【参考方案1】:

假设您使用的是 Express,您的答案归结为这一点

app.use(function(req,res)  res.setHeader("Access-Control-Allow-Origin", "*"); next(); );

这将非常简单地在向节点服务器发出的每个请求上输出 CORS 标头。很简单吧?请记住注意事项:

不适用于 IE6 和 7,尽管 jQuery 弥补了这一点 不允许您微调访问。您可以通过在各种路由中调用 setHeder 来对其进行微调。 您应该使用反向代理来避免这种情况。

【讨论】:

我仍然遇到同样的错误:Exception... "Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)" location: "http://api.localhost:8080/myCleanAPI.js Line: 6"] constructor=DOMException, filename= "http://api.localhost:8080/myCleanAPI.js" , code= 1012 , 您能在导航器的网络选项卡上看到查询结果吗?标题是否存在? 不,我没有看到任何结果,因此它甚至没有执行。我只能看到,我的 JS api 是如何加载的。 如果不执行,你的浏览器不支持CORS。 IE7 还是 IE8,有机会吗? 我在 Ubuntu 12 上使用 Firefox 16

以上是关于CORS on node subdomain的主要内容,如果未能解决你的问题,请参考以下文章

Angular/Node/Express/Passport 跨域问题 - 启用 CORS Passport Facebook 身份验证

反应前端,节点后端CORS问题[关闭]

AngularJS on Rails 中的 CORS 问题

Node.JS OvernightJS Express CORS XMLHttpRequest 已被 CORS 策略阻止

javascript [在服务器上启用CORS]允许服务器请求CORS #javascript #node #cors

在 Ruby on Rails 中允许 CORS