20、express跨域配置,session处理,vue---asiox跨域处理cookie

一、express跨域配置

app.js

//设置跨域请求
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

二、session处理

var cookieSession = require("cookie-session");
var keys = [];
for(var i = 0; i < 10000; i++){
	keys.push("sessionid"+Math.random());
}

app.use(cookieSession({
	name:"sessionId",
	keys,
	maxAge:30*60*1000 //ms
}))

三、存储cookie

后台此为注册验证码接口

npm i -S svg-captcha

const svgCaptcha = require('svg-captcha');
router.get('/getCode',(req,res)=>{
  var codeConfig = {
    size: 5,// 验证码长度
    ignoreChars: '0o1i', // 验证码字符中排除 0o1i
    noise: 2, // 干扰线条的数量
    color: true,
    background: '#cc9966',
    height: 40,
    width: 100
  }
  const captcha = svgCaptcha.createMathExpr(codeConfig);
  req.session.captcha = captcha.text.toLocaleLowerCase(); // session 存储
  res.type('svg'); // 响应的类型
  res.send(captcha.data);
});

使用时直接req.session.captcha

前端 vue项目 axios请求

withCredentials设置为true,可以在单个请求设置,也可全局设置。
设置为true,本地才会存储,接口请求头才会带cookie

全局:axios.defaults.withCredentials = true

浏览器的cookie是HttpOnly,不能被js读取。

注 withCredentials设置为true请求头设置cookie,响应头存储cookie,可以跨域。但后台,res.header("Access-Control-Allow-Origin", " * "); 不能用'*',需用固定的地址
后台express设置下

1、动态设置Access-Control-Allow-Origin

let originHeader=req.headers.origin;
res.header("Access-Control-Allow-Origin", originHeader);

2、Access-Control-Allow-Credentials设为true

res.header("Access-Control-Allow-Credentials", true);

代码如下

//设置跨域请求
app.all('*', function (req, res, next) {
  let originHeader=req.headers.origin;
  res.header("Access-Control-Allow-Origin", originHeader);
  // res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  res.header("Access-Control-Allow-Credentials", true);
  next();
});

这样就可以了

session

posted @ 2020-04-14 13:12  飞刀还问情  阅读(882)  评论(0编辑  收藏  举报