这是我的设置: - 我在 nodejs 中实现了一个 http 服务器,它公开了 api 端点。这是通过 nginx 反向代理到api.domain.com
ssl。这是配置:
1 server {
2 listen 80;
3 server_name api.domain.com;
4 access_log /var/log/nginx/api.access.log;
5 location / {
6 proxy_pass http://127.0.0.1:3000/;
7 }
8 }
9
10 server {
11 listen 443;
12 server_name api.domain.com;
13 access_log /var/log/nginx/api.access.log;
14 ssl on;
15 ssl_certificate /path/to/ssl/server.crt;
16 ssl_certificate_key /path/to/ssl/server.key;
17 location / {
18 proxy_pass https://127.0.0.1:3001/;
19 }
20 }
然后我让 nginx 在其下提供一个静态上下文文件,dashboard.domain.com
该文件旨在使用来自api.domain.com
. 这是设置:
1 server {
2 listen 80;
3 server_name dashboard.domain.com;
4 root /path/to/static/site;
5 }
我想使用 CORS 来执行此操作,我确保静态站点上的 jsOrigin
在所有请求中发送正确的标头。我实现了一个非常简单的登录机制。这是我在 api 端点上使用的咖啡脚本代码:
# server.coffee
app.configure ->
app.use middleware.setP3PHeader()
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.session
secret: conf.session.secret
key: conf.session.key
cookie:
maxAge: conf.session.maxAge
app.use express.methodOverride()
app.use express.query()
app.use express.errorHandler()
# routes.coffee
app.options '*', shop.cors, shop.options
app.post '/login', shop.cors, shop.login
app.post '/logout', shop.cors, shop.logout
app.get '/current-user', shop.cors, shop.current
# shop.coffee
exports.options = (req, res) ->
res.send 200
exports.cors = (req, res, next) ->
allowed = ['http://dashboard.domain.com', 'http://localhost:3000']
origin = req.get 'Origin'
if origin? and origin in allowed
res.set 'Access-Control-Allow-Origin', origin
res.set 'Access-Control-Allow-Credentials', true
res.set 'Access-Control-Allow-Methods', 'GET,POST'
res.set 'Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'
next()
else
res.send 403, "Not allowed for #{origin}"
exports.login = (req, res) ->
unless req.body.email? and req.body.password?
res.send 400, "Request params not correct #{req.body}"
models.Shop.findOne()
.where('email').equals(req.body.email)
.where('password').equals(req.body.password)
.exec (err, shop) ->
if err? then return res.send 500, err.message
unless shop? then return res.send 401, "Not found for #{req.body}"
req.session.shopId = shop.id
res.send 200, shop.publish()
exports.logout = (req, res) ->
delete req.session.shopId
res.send 200
exports.current = (req, res) ->
unless req.session.shopId?
return res.send 401, "Not logged in!"
models.Shop.findById(req.session.shopId)
.exec (err, shop) ->
if err? then return send.res 500, err.message
unless shop? then return res.send 404, "No shop for #{req.session.shopId}"
res.send 200, shop.publish()
问题是这样的: 1. 我第一次打电话给/login
我,我得到了一个与登录用户的新会话 ( req.session.shopId
) 2. 然后我打电话/current-user
但会话消失了!nodejs服务器收到的会话ID不同,因此它创建了一个不同的会话