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

前端 | 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.dtcms.com/a/60071.html

相关文章:

  • Linux上位机开发实战(开篇)
  • 认识vue2脚手架
  • LangChain4j开发RAG入门示例
  • Unity Dots从入门到精通之 Prefab引用 转 实体引用
  • QT:TCP示例
  • linux查看定时任务与设置定时任务
  • C#的判断语句总结
  • C++面试题:C++怎么避免头文件循环引用?
  • 游戏引擎学习第146天
  • 学习小程序开发--Day1
  • 学习网络安全需要哪些基础?
  • C++单例进化论
  • P8686 [蓝桥杯 2019 省 A] 修改数组--并查集 or Set--lower_bound()的解法!!!
  • 设计模式 一、软件设计原则
  • Spring源码探析(二):BootstrapContext初始化深度解析(默认配置文件加密实现原理)
  • [算法笔记]cin和getline的并用、如何区分两个数据对、C++中std::tuple类
  • uniapp版本加密货币行情应用
  • Unity DOTS从入门到精通之EntityCommandBufferSystem
  • C#模拟鼠标点击,模拟鼠标双击,模拟鼠标恒定速度移动,可以看到轨迹
  • 【vitepress】如何搭建并部署自己的博客网站
  • sqlserver中的锁模式 | SQL SERVER如何开启MVCC(使用row-versioning)【启用行版本控制减少锁争用】
  • 基于单片机的智慧农业大棚系统(论文+源码)
  • mysql(community版)压缩包安装教程
  • 【计算机网络】确认家庭网络是千兆/百兆带宽并排查问题
  • 解决电脑问题(5)——鼠标问题
  • Android SharedPreferences 工具类封装:高效、简洁、易用
  • MySql数据库增删改查常用语句命令-MySQL步骤详解教程
  • Docker 的基本概念和优势,以及在应用程序开发中的实际应用
  • (十七) Nginx解析:架构设计、负载均衡实战与常见面试问题
  • windows环境下安装部署dify+本地知识库+线上模型