前端(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 //设置cookie 21 exports.setCookie = function(res,key,value){ 22 res.cookie(key, value, { 23 maxAge: config.maxAge, 24 httpOnly: true, 25 //只允许在https协议下传输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.启动时绑定中间件
require('./lib/cookie').initCookie(app);
3.接口调用处理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 //设置cookie 10 cookie.setCookie(res,'name','xjytest'); 11 res.send('OK'); 12 }) 13 14 }
通过以上设置,Express Restful API 可以自由的设置和调用前端的cookie了。