我有一個節點服務器,它響應請求並根據主機頭重定向用戶。用法是靜態/主頁網站位於www,每個用戶都有自己的子域(即www.example.com和site.example.com)。路由是按照site.js。使用Express和Node,如何在子域/主機頭之間維護會話
當用戶沒有登錄時,他們被重定向到登錄。
我發現當用戶被重定向到他們的子域時,會話不會被維護。我想這是預期的,但我想知道是否有辦法在兩個子域中維護同一個會話。
我一直希望,如果他們登錄並返回到www.example.com,他們會看到一個不同的視圖,其中包括一個鏈接註銷/他們的儀表板等。我現在的解決方法,我想,只是在他們的子域創建會話,如果他們確實返回www它就好像他們沒有登錄。
任何人之前處理過或有如何處理這種方式的會話的答案?
我認爲這個問題可能是users.js,我重定向到「http://site.example.com」作爲它不是一個相對路徑...
下面是相關代碼(用戶查找使用MongoDB的做,我已經離開它作爲其做工精細 - 調用該服務是users.authenticate)行...
server.js:
app.configure ->
app.set "views", "#{__dirname}/views"
app.set "view engine", "jade"
app.use express.bodyParser()
app.use express.methodOverride()
app.use express.cookieParser()
app.use express.session {
key: "KEY",
secret: "SECRET",
store: new MemoryStore(),
cookie: {
domain: 'example.com',
maxAge : 1000*60*60*24*30*12
}
}
app.use express.static "#{__dirname}/public"
app.use express.logger "short"
app.use express.favicon "#{__dirname}/public/img/favicon.ico"
app.use app.router
site.js:
module.exports = (app) ->
app.get '/', (req, res) ->
console.log "/ hit with #{req.url} from #{req.headers.host}"
domains = req.headers.host.split "."
org = if domains then domains[0] else "www"
if org == "www"
res.render "index", { layout: null }
else
if req.session.user
console.log "session established"
res.render "app", { layout: null }
else
console.log "no session"
res.redirect "http://www.example.com/accounts/login"
個
users.js:
users = require('../services/users')
module.exports = (app) ->
app.get "/accounts/login", (req, res) ->
res.render "login", { layout: null, locals: { returnUrl: req.query.returnUrl } }
app.post "/accounts", (req, res) ->
users.authenticate app, req.body.login, req.body.password, (user) ->
if user
req.session.user = user
res.redirect "http://#{user.orgName}.example.com"
else
res.render "login", { layout: null, locals: { returnUrl: req.body.url } }
app.get "/accounts/logout", (req, res) ->
console.log "deleting user from session"
delete req.session.user
res.redirect "http://www.example.com
本地測試它在OSX,我已經加入www.example.com和site.example.com在我的hosts文件,使DNS查找得到本地處理。
用戶'$ .ajaxSetup'爲每個請求添加'withCredentials:true' – Xerri 2013-07-15 08:09:48
@Maksims「使用域名在本地主機上不會很好地工作」 - 爲什麼它不能在localhost上運行?我有:api.localhost:3000和localhost:3000 - 不工作? :\ – AmpT 2014-02-27 13:01:21
由於瀏覽器的安全性,如果當前域與其定義的域不匹配,cookie將不會被髮送。對於開發和舞臺環境,您可以註釋掉域屬性,或將其設置爲「本地主機」。 – moka 2014-02-28 01:07:34