赞
踩
确保在后端正确配置 CORS 中间件,允许跨域请求并支持凭据传递。
假设你使用的是 Express.js,可以这样设置:
- const express = require('express');
- const cors = require('cors');
- const app = express();
-
- // CORS 配置
- const corsOptions = {
- origin: 'http://localhost:5173', // 允许的前端地址
- credentials: true, // 允许发送 cookie
- };
-
- app.use(cors(corsOptions));
-
- // 示例路由
- app.post('/api/teachers/login', (req, res) => {
- const token = tokenEncode(data); // 生成 JWT
- res.cookie('token', token, {
- maxAge: 30 * 24 * 60 * 60 * 1000, // 30 天
- httpOnly: true, // 仅通过 HTTP 访问,防止 XSS 攻击
- secure: true, // 仅在 HTTPS 下发送
- sameSite: 'None' // 允许跨站点发送 cookie
- });
- res.json({ message: 'login success' });
- });
-
- app.listen(8080, () => {
- console.log('Server is running on port 8080');
- });

确保在前端的请求中包含 credentials: 'include'
,这样可以发送和接收 cookie。
- fetch('http://localhost:8080/api/teachers/login', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- credentials: 'include', // 允许发送和接收 cookie
- body: JSON.stringify({
- // 你的请求数据
- name: this.name,
- sex: this.sex,
- school: this.school,
- className: this.className, // 修改为className
- phone: this.phone,
- password: this.password,
- subject: this.array[this.index],
- ismaster: this.ismaster
- })
- })
- .then(response => response.json())
- .then(data => {
- console.log('后端响应结果:', data);
- })
- .catch(error => console.error('请求失败:', error));

确保后端和前端的域名、端口号正确:确保在 CORS 设置中的 origin
与前端请求的地址一致。
检查预检请求(OPTIONS 请求):有时浏览器会先发送一个预检请求(OPTIONS 请求)来检查服务器是否允许实际请求。如果预检请求失败,实际请求就会被阻止。确保后端正确处理 OPTIONS 请求。
app.options('/api/teachers/login', cors(corsOptions)); // 处理预检请求
HTTPS 配置:如果你在开发环境中使用 HTTPS,需要确保 secure
设置为 true
。在本地开发环境中,可以暂时设置为 false
进行调试。
通过这些配置,可以解决 CORS 问题,并允许前端正确接收来自后端的 cookie
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。