当前位置: 首页 > news >正文

axios发送请求,后端无法获取cookie

1.前端

axios默认不携带cookie

添加如下代码

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

app.enableCors({//不用localhostorigin: '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中


//发送验证码@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.textreq.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,导致一直获取不到

http://www.lryc.cn/news/390984.html

相关文章:

  • 【Spring Boot 源码学习】初识 ConfigurableEnvironment
  • 开关电源中强制连续FCCM模式与轻载高效PSM,PFM模式优缺点对比笔记
  • 5分钟教你用AI把老照片动起来,别再去花49块9的冤枉钱了
  • Ruby 环境变量
  • BPF:BCC工具 funccount 统计内核函数调用(内核函数、跟踪点USDT探针)认知
  • DPO算法推导
  • Qt源码分析:窗体绘制与响应
  • docker 安装 禅道
  • 【简要说说】make 增量编译的原理
  • DETRs Beat YOLOs on Real-time Object Detection论文翻译
  • SpringBoot 多数据源配置
  • RK3568驱动指南|第十六篇 SPI-第192章 mcp2515驱动编写:完善write和read函数
  • #BI建模与数仓建模有什么区别?指标体系由谁来搭建?
  • 如何用Python实现三维可视化?
  • chrome.storage.local.set 未生效
  • 泛微开发修炼之旅--30 linux-Ecology服务器运维脚本
  • LeetCode 全排列
  • python实现支付宝异步回调验签
  • 注意!Vue.js 或 Nuxt.js 中请停止使用.value
  • Java:JDK、JRE和JVM 三者关系
  • Radio专业术语笔记
  • cocosCreator找出未用到的图片
  • 一览 Anoma 上的有趣应用概念
  • Spring Boot集成fastjson2快速入门Demo
  • Three.js机器人与星系动态场景(二):强化三维空间认识
  • java顺序查找
  • 提升学生职务执行力的智慧校园学工管理策略
  • 系统运维面试总结(shell编程)
  • 在数据库中,什么是主码、候选码、主属性、非主属性?
  • Linux-笔记 udev机制介绍