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

前端 | CORS 跨域问题解决

问题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:3000Access-Control-Allow-Origin 头部没有配置,导致请求被浏览器拦截


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

①修改后端
(假设是 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的顺序

 


http://www.kler.cn/a/578664.html

相关文章:

  • 基于ESP32的Python物联网开发实践 - 通过HTTP API控制LED灯
  • Windows下配置Flutter移动开发环境以及AndroidStudio安装和模拟机配置
  • 策略设计模式-下单
  • 【练习】PAT 乙 1061 判断题
  • p5.js:sound(音乐)可视化,动画显示音频高低变化
  • FastAPI 请求体参数与 Pydantic 模型完全指南:从基础到嵌套模型实战 [特殊字符]
  • 长方形旋转计算最后的外层宽高
  • JAVA实战开源项目:大学城水电管理系统(Vue+SpringBoot) 附源码
  • spring 和JVM之间关系
  • 【AI论文】GEN3C: 基于3D信息的全球一致视频生成技术,实现精确相机控制
  • Ubuntu 下 Docker 企业级运维指南:核心命令与最佳实践深度解析20250309
  • 51单片机Proteus仿真速成教程——P1-软件与配置+Proteus绘制51单片机最小系统+新建程序模版
  • 十二、Redis Cluster(集群)详解:原理、搭建、数据分片与读写分离
  • 查看电脑信息
  • C++:入门详解(关于C与C++基本差别)
  • [css教程]2025系统全面css教程(四)
  • 【redis】数据类型之geo
  • vs code 设置字体颜色
  • 大模型架构记录3-提示工程
  • VBA使用fso对象合并指定路径的txt文件(含子目录)