前端 | CORS 跨域问题解决

06-01 1411阅读

问题:Access to fetch at 'http://localhost:3000/save' from origin 'http://localhost:5174' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.。

分析:CORS (跨域请求) 被拦截 —— http://localhost:5174 请求 http://localhost:3000,但 Access-Control-Allow-Origin 头部没有配置,导致请求被浏览器拦截。

前端 | CORS 跨域问题解决


 解决:前端可以尝试进行跨域请求。

①修改后端
(假设是 Express): 在 server.js(或 index.js)中添加:
// 记得ctrl+shift+y打开终端,在里头运行 npm install cors
const cors = require("cors"); 
app.use(cors());
(假设包管理中的  "type": "module")
// 记得ctrl+shift+y打开终端,在里头运行 npm install cors
import cors from 'cors';
app.use(cors());
根据情况,是  express服务器 还是 "type": "module",判断是用require还是import
②手动设置响应头:
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'http://localhost:5174');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    if (req.method === 'OPTIONS') {
      return res.status(200).end();
    }
    next();
  });

 或者

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");  // 或指定特定前端地址
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});

 ③如果后端无法修改,可以在 fetch 请求中加入 mode: "cors":
const response = await fetch("http://localhost:3000/save", {
  method: "POST",
  mode: "cors",  // 添加 CORS 模式
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ content: text })
});

完整代码:

import cors from 'cors';
import express from 'express';
const app = express();
const PORT = 3000;  // 后端服务器端口
// 允许跨域请求
app.use(cors({
    origin: 'http://localhost:5174', // 允许的前端域名
    methods: ['GET', 'POST'],    // 允许的请求方法
    allowedHeaders: ['Content-Type', 'Authorization'],  // 允许的请求头
})); 
// 额外的跨域处理
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'http://localhost:5174');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    if (req.method === 'OPTIONS') {
      return res.status(200).end();
    }
    next();
  });
app.use(express.json());    // 解析JSON请求体
// 添加 get请求,检查后端是否正常运行
app.get('/',  (req, res) => {
  res.send('√后端运行正常!');
});

注: 注意顺序,press和cors的顺序

 

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。

相关阅读

目录[+]

取消
微信二维码
微信二维码
支付宝二维码