express如何解決ajax跨域訪問session失效問題詳解
前言
最近在學(xué)習(xí)express,就用以前做的項(xiàng)目來進(jìn)行express前后端分離的練手了,在做登陸注冊(cè)的時(shí)候發(fā)現(xiàn)跨域的時(shí)候,session的值是會(huì)失效的,導(dǎo)致session里面的數(shù)據(jù)獲取為undefined,網(wǎng)上找資料加上自己的不斷嘗試,終于找到了解決方法,簡(jiǎn)單記錄一下解決方法。
解決方法
1、客戶端因?yàn)閟ession原則上是需要cookie支持的,所以Ajax方法里面必須添加 xhrFields:{withCredentials:true},表示允許帶Cookie的跨域Ajax請(qǐng)求( 特別說明,只要使用的session都得加這句)
$('#login').click(function () { $.ajax({ url: 'http://localhost:3000/users/yzm',//服務(wù)端路由地址 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();/!*阻止表單默認(rèn)事件,頁面全局刷新*!/ var data=$('#form_login').serialize();/!*將表單里的數(shù)據(jù)包裝起來*!/ $.ajax({ url : 'http://localhost:3000/users/login', type : "post", data : data, xhrFields:{withCredentials:true}, dataType:'json', success:function(msg) { alert("這是返回的數(shù)據(jù)"+msg); }, error:function(err){ alert("這是失敗的信息"+err); } }); });
通過設(shè)置 withCredentials: true ,發(fā)送Ajax時(shí),Request header中便會(huì)帶上 Cookie 信息。
2、服務(wù)器端修改app.js文件
相應(yīng)的,對(duì)于客戶端的參數(shù),服務(wù)器端也需要進(jìn)行設(shè)置。
對(duì)應(yīng)客戶端的 xhrFields.withCredentials: true 參數(shù),服務(wù)器端通過在響應(yīng) header 中設(shè)置 Access-Control-Allow-Credentials = true 來運(yùn)行客戶端攜帶證書式訪問。通過對(duì) Credentials 參數(shù)的設(shè)置,就可以保持跨域 Ajax 時(shí)的 Cookie。
var express = require('express'); var session = require('express-session');/*引入會(huì)話變量*/ 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(); });
特別注意:服務(wù)器端 Access-Control-Allow-Credentials = true時(shí),參數(shù)Access-Control-Allow-Origin 的值不能為 '*' ,必須為自己客戶端項(xiàng)目所在地址。
3、服務(wù)器中使用session
router.get('/yzm', function(req, res, next) { req.session.yzm='abcd'; } router.post('/login', function(req, res, next) { console.log(req.session.yzm); }
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
npm出現(xiàn)Cannot?find?module?'XXX\node_modules\npm\bin\np
最近在啟動(dòng)項(xiàng)目的時(shí)候會(huì)報(bào)這個(gè)錯(cuò)就是npm丟失,所以下面這篇文章主要給大家介紹了關(guān)于npm出現(xiàn)Cannot?find?module?'XXX\node_modules\npm\bin\npm-cli.js'錯(cuò)誤的解決方法,需要的朋友可以參考下2022-08-08Node.js連接mongo數(shù)據(jù)庫上傳文件的方法步驟
本文主要介紹了Node.js連接mongo數(shù)據(jù)庫上傳文件的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05