<button>点我获取到cookie</button>
<button>点我发送cookie</button>
<script>
let d = document.querySelectorAll("button");
d[0].onclick = function(){ //用于发起get请求获取cookie
$.ajax({
url:'/get_nanoid',
method:'GET',
success:function(res){
console.log("获取到了cooki",res);
}
})
}
d[1].onclick = function(){
$.ajax({
url:'/get_nanoid',
method:'POST',
headers:{'X-CSRFToken': //将获取cookie的设置请求头用于crsf验证
document.cookie.substr(document.cookie.lastIndexOf('crsf_token')+'crsf_token'.length+1,48)},
success:function(res){
console.log(res);
console.log('成功');
}
})
}
const { nanoid } = require("nanoid")
const cookieParser = require("cookie-parser")//用于解析req.cookies["crsf_token"]
app.get("/get_nanoid",(req,res)=>{
let crsf_token = nanoid(48); //nanoid生成随机token
res.cookie("crsf_token",crsf_token) //当发送get请求时返回带有token的cookie
res.send("1");
})
app.post("/get_nanoid",(req,res)=>{
console.log(req.cookies["crsf_token"]);
console.log(req.headers['x-csrftoken']);
if(req.cookies["crsf_token"] === req.headers['x-csrftoken']){
console.log("1");
res.send("验证通过");
}else{
console.log("验证失败");
}
})
nanoid最新版本为4,直接安装会发生错误 使用 npm i nanoid@3安装3版本就可以