以下内容均基于nodejs的express框架进行描述
cookie的获取和设置 nodejs安装cookie-parser,用于解析cookie
1 2 3 4 npm i cookie-parser const cookieParser = require ('cookie-parser' )app.use(cookieParser());
以登录接口为例子
1 2 3 4 5 6 7 8 9 //登录 app.post('/login',(req,res) => { res.cookie('add','add',{maxAge: 900000,httpOnly: true}) }) //检验登录 app.get('/loginCheck',(req,res) => { console.log(req.cookies.add); })
跨域请求情况下的cookie ajax同源请求默认是会自动带上cookie,ajax跨域请求默认是不会自动带上cookie
需要采取下列方法(基于CORS):
前端请求需设置:
1 2 3 4 const xhr = new XMLHttpRequest();xhr.withCredentials = true jquery: $ajax({xhrFields :{withCredentials :true }})
服务器需设置header:
1 2 3 4 5 6 7 8 9 10 11 12 13 app.use((req,res,next ) => { res.header('Access-Control-Allow-Headers' ,'a' ); res.header('Access-Control-Expose-Headers' ,'b' ) res.header('Access-Control-Allow-Origin' ,'http://localhost:3000' ); res.header('Access-Control-Allow-Methods' ,'get,post' ); res.header('Access-Control-Allow-Credentials' ,true ); next(); })
也可借助cors插件
1 2 3 4 5 6 7 8 9 10 11 12 13 const cors = require ('cors' ) app.use(cors({ allowedHeaders: 'a' , exposedHeaders: 'b' , credentials: true , methods: 'GET' , origin: 'http://localhost;3000' })) app.use('/get' ,cors(),(req,res,next) =>{})
This is copyright.