1. 程式人生 > >express解決ajax跨域訪問session失效問題

express解決ajax跨域訪問session失效問題

最近在學習express,就用以前做的專案來進行express前後端分離的練手了,在做登陸註冊的時候發現跨域的時候,session的值是會失效的,導致session裡面的資料獲取為undefined,網上找資料加上自己的不斷嘗試,終於找到了解決方法,簡單記錄一下解決方法。
1、客戶端因為session原則上是需要cookie支援的,所以Ajax方法裡面必須新增 xhrFields:{withCredentials:true},表示允許帶Cookie的跨域Ajax請求( 特別說明,只要使用的session都得加這句)

   $('#login').click(function () {
        $.ajax({
            url: 'http://localhost:3000/users/yzm',//服務端路由地址
            type: 'get',
            xhrFields:{withCredentials:true},
            dataType: 'json',
            success:function(data){
                $('#yzm_img').html(data)
            },
            error:function(){
                alert('error');
            }
        });
    });
    $('#form_login').submit(function (e) {/!*登入*!/
        e.preventDefault();/!*阻止表單預設事件,頁面全域性重新整理*!/
        var data=$('#form_login').serialize();/!*將表單裡的資料包裝起來*!/
        $.ajax({
            url : 'http://localhost:3000/users/login',
            type : "post",
            data : data,
            xhrFields:{withCredentials:true},
            dataType:'json',
            success:function(msg) {
                alert("這是返回的資料"+msg);
            },
            error:function(err){
                alert("這是失敗的資訊"+err);
            }
        });
    });

通過設定 withCredentials: true ,傳送Ajax時,Request header中便會帶上 Cookie 資訊。
2、伺服器端修改app.js檔案
相應的,對於客戶端的引數,伺服器端也需要進行設定。
對應客戶端的 xhrFields.withCredentials: true 引數,伺服器端通過在響應 header 中設定 Access-Control-Allow-Credentials = true 來執行客戶端攜帶證書式訪問。通過對 Credentials 引數的設定,就可以保持跨域 Ajax 時的 Cookie。

var express = require('express');
var session = require('express-session');/*引入會話變數*/

var app = express();
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:63342");//前端域名
    res.header("Access-Control-Allow-Credentials",'true');
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();
});

特別注意:伺服器端 Access-Control-Allow-Credentials = true時,引數Access-Control-Allow-Origin 的值不能為 '*' ,必須為自己客戶端專案所在地址。
3、伺服器中使用session

router.get('/yzm', function(req, res, next) {
    req.session.yzm='abcd';
}
router.post('/login', function(req, res, next) {
 console.log(req.session.yzm);
}