Express框架Restful API Ajax 跨域 开启Cookie支持
生活随笔
收集整理的這篇文章主要介紹了
Express框架Restful API Ajax 跨域 开启Cookie支持
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前端(Jquery Ajax):
1 $.ajax({ 2 url: "http://localhost/api/test/", 3 type: "POST", 4 xhrFields: { 5 withCredentials: true //必須添加 6 }, 7 crossDomain: true, //必須添加 8 success: function (data) { 9 alert(data); 10 } 11 });Node.js:
1.Cookie操作庫(cookie.js):
1 'use strict'; 2 //依賴 cookie-parser 模塊 3 4 var cookieParser = require('cookie-parser'); 5 var config = { 6 isUseCookieSign:false, //是否使用cookie加密 7 sign:'cookieSecret', //cookie加密字符 8 maxAge:900000 //cookie失效時間 9 }; 10 11 exports.initCookie = function(app){ 12 //如果開啟cookie加密 13 if(config.isUseCookieSign){ 14 app.use(cookieParser(config.sign)); 15 } else{ 16 app.use(cookieParser()); 17 } 18 19 } 20 //設(shè)置cookie 21 exports.setCookie = function(res,key,value){ 22 res.cookie(key, value, { 23 maxAge: config.maxAge, 24 httpOnly: true, 25 //只允許在https協(xié)議下傳輸cookie 26 // secure:true, 27 signed: config.isUseCookieSign 28 }); 29 } 30 //獲取cookie 31 exports.getCookie = function(req,key){ 32 if(config.isUseCookieSign){ 33 if(req.signedCookies[key] === undefined){ 34 return null; 35 } else{ 36 return req.signedCookies[key]; 37 } 38 39 } else{ 40 if(req.cookies[key] === undefined){ 41 return null; 42 } else{ 43 return req.cookies[key]; 44 } 45 46 } 47 } 48 //刪除cookie 49 exports.delCookie = function(res,key){ 50 res.clearCookie(key); 51 }2.啟動時綁定中間件和設(shè)置http response header
//綁定中間件require('./lib/cookie').initCookie(app);
//設(shè)置http header
app.use(
function (req, res, next) {
//設(shè)置返回頭
res.set({
'Access-Control-Allow-Origin':'http://localhost',//設(shè)置允許的域
'Access-Control-Allow-Credentials':'true' //允許發(fā)送Cookie
});
next();
}
);
3.接口調(diào)用處理cookie
1 'use strict'; 2 var cookie = require('../../lib/cookie'); //cookie庫引用 3 4 exports.bind = function (app, preUrl) { 5 6 app.post(preUrl+'/',function(req,res,next){ 7 //獲取cookie 8 console.log(cookie.getCookie(req,'name')); 9 //設(shè)置cookie 10 cookie.setCookie(res,'name','xjytest'); 11 res.send('OK'); 12 }) 13 14 }通過以上設(shè)置,Express Restful API 可以自由的設(shè)置和調(diào)用前端的cookie了。
?
轉(zhuǎn)載于:https://www.cnblogs.com/sheryee/p/10688535.html
總結(jié)
以上是生活随笔為你收集整理的Express框架Restful API Ajax 跨域 开启Cookie支持的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 正则表达式三种模式:贪婪模式、懒惰模式、
- 下一篇: JAVA面向对象程序设计(第二版) 袁绍