节点子域上的CORS

时间:2013-05-14 14:13:55

标签: javascript node.js api express cors

我正在尝试在子域上设置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;

main.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;

1 个答案:

答案 0 :(得分:0)

假设您正在使用Express

,您的答案归结为此
app.use(function(req,res) { res.setHeader("Access-Control-Allow-Origin", "*"); next(); });

这将非常简单地在对节点服务器发出的每个请求上输出CORS头。简单,对吧?请记住警告:

  • 虽然jQuery补偿了
  • ,但对IE6和7不起作用
  • 不允许您微调访问权限。您可以通过将setHeder调用到各种路径来对其进行微调。
  • 你应该反向代理以避免这种情况。