使用 koa2 + koa-session, vue 2.6.11 + axios + ant-design-vue 模拟客户端登录
- 使用 postman 可以存储cookie,每次都可以带上cookie请求,并且返回登录成功的数据
- 使用vue,可以返回成功登录的数据,却无法在 chrome/devTool/cookies 中看到写入的cookie数据
请问会有什么原因导致这种情况呢?
服务器端部分代码:
// 用户不存在 if (!matchData.user) { return ctx.body = { success: false, err: "用户不存在" } } ctx.session.user = { _id: matchData.user._id, email: matchData.user.email, role: matchData.user.role, username: matchData.user.username } ctx.body = { success: true, body: ctx.session }
客户端请求代码
import axios from 'axios' function http(config) { const instance = axios.create({ baseURL: "http://localhost:3000", timeout: 10000 }); instance.interceptors.request.use(config => { return config; }, error => { return Promise.reject(error); }) instance.interceptors.response.use(response => { return response; }, error => { return Promise.reject(error); }) return instance(config); } export function request(params) { return http({ url: "/admin/login", method: "post", data: params }) }
已解决
悬赏分:40
- 解决时间 2021-11-27 22:30
点赞 0反对 0举报 0
收藏 0
分享 0
回答2
最佳
-
axios使用data的方式发送数据, 需要设置 transformRequest,如下:
transformRequest: [ function (data) { let ret = ''; for (let it in data) { ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'; } return ret; } ]
如果需要带着cookie发送数据,需要设置 withCredentials 为 true,所有配置如下:
{ url: "/admin/login", method: "post", headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }, transformRequest: [ function (data) { let ret = ''; for (let it in data) { ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'; } return ret; } ], data: { "email": params.email, "password": params.password }, withCredentials: true }
!!!如果存在跨域问题,需要到服务器设置允许域,或者设置webapck代理
设置了 withCredentials: true,则Access-Control-Allow-Origin不能设置为*参考:https://blog.csdn.net/nnsword...
支持 0 反对 0 举报2021-11-27 05:55