1.前端
axios默认不携带cookie
添加如下代码
TypeScript
import axios from "axios"
const requrst = axios.create({
baseURL: import.meta.env.VITE_APP_URL,
timeout: 5000,
})
//让axios携带cookie
requrst.defaults.withCredentials = true
2.后端nestjs
main.ts
TypeScript
app.enableCors({
//不用localhost
origin: 'http://127.0.0.1:5173', // 允许跨域源
credentials: true,//允许携带
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
})
app.use(session({
secret: 'yyds',
name: "delicious",
resave: false,
saveUninitialized: false,
cookie: { maxAge: 999999 }
}))
在新建的user.controller.ts中
TypeScript
//发送验证码
@Get('code')
Code(@Req() req, @Res() res, @Session() session) {
const CodeImg = svgCaptcha.create({
size: 4,
fontSize: 50,
color: true,
background: 'black',
inverse: true,
width: 100
})
//保存验证码
session.code = CodeImg.text
req.session.delicious = "ddddd"
// console.log(req.session)
res.type('image/svg+xml')
res.send(CodeImg.data)
}
//测试
@Post()
async create(@Body() body: User_add, @Res() res, @Session() session, @Req() req) {
//不要用localhost,也不要写*
res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5173");
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD,PUT");
res.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
//关键配置
res.setHeader("Access-Control-Allow-Credentials", "true")
console.log(req.session)
res.send({
ok: "ok"
})
}
主要的问题就是使用了localhost,而不是127.0.0.1,导致一直获取不到