javascript - CORS on node subdomain -
i trying set api on sub domain , because of try set javascript api after web api.
but unfortunally getting error after trying reach server on xmlhttprequest()
.
i have been trying set sub domain express server ways have found allowing cors, still same error.
update:
here files:
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 , 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 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 response otherwise username not found if (data) { //check if user blocked if (data.blocked ? data.blocked : false) { res.send(200, {"state": false, "reason": "you blocked system"}); } else { //checks if password same in db if (data.password == password) { //creating content of token var atoken = tool.randomstring(25); //checking if acccess token should 7 days or session token /* not needed in api if (req.body.inputcheckbox) { //send cookie lasts 7 days user res.cookie('token', atoken, {expires: new date(date.now() + 604800000) , httponly: true, signed: true}); } else { //send session cookie user res.cookie('token', atoken, {maxage: null, httponly: true, signed: true}); } */ //redirection / //res.redirect("/"); res.send(200, {"state": true, "atoken": atoken, "id": data._id}); //set user online, save ip ,date of last login , 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 false password var attempt = data.attempt ? data.attempt : 0; //if attempts more equals 5 user gets blocked if (attempt >= 5) { res.send(200, "blocked"); //set user 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 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 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 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 user 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 created - uid ( user identification) var rand = tool.randomstring(20); //save request in 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 given email link reset 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 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 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 running'); exports.app = app;
and 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 resource"); }); console.log("main server running"); exports.app = app;
your answer boils down this, assuming you're using express
app.use(function(req,res) { res.setheader("access-control-allow-origin", "*"); next(); });
this quite output cors header on every request made node server. simple, huh? bear in mind caveats:
- does not work ie6 , 7, though jquery compensates that
- does not allow fine-tune access. can fine-tune taking setheder call various routes.
- you should reverse proxying avoid this.
Comments
Post a Comment