服务器运维(六)跨域配置 Preflight 问题——东方仙化神期

正确配置

python

复制代码
| **Python(Django)** | 在 `settings.py` 中配置:
```python
INSTALLED_APPS = [
    # ...
    'corsheaders',
    # ...
]

MIDDLEWARE = [
    # ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    # ...
]

CORS_ALLOWED_ORIGINS = ['https://your-frontend.com']  # 生产环境指定前端域名
CORS_ALLOW_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
CORS_ALLOW_HEADERS = ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization']
``` |
| **Java(Spring Boot)** | 编写配置类:
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("https://your-frontend.com") // 生产环境指定前端域名
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization")
                .allowCredentials(true) // 若需携带凭证,开启此选项
                .maxAge(3600); // 预检请求结果缓存时间(秒)
    }
}
``` |


### 三、前端无需额外操作(浏览器自动处理)
前端发起跨域请求时,浏览器会**自动触发 Preflight 预检**,无需开发者手动发送 OPTIONS 请求。只需确保请求的方法、自定义头与服务端配置的 `Access-Control-Allow-Methods`、`Access-Control-Allow-Headers` 匹配即可。


通过以上配置,服务端就能正确响应 Preflight 预检请求,浏览器会在预检通过后执行实际的业务请求,从而解决跨域问题。

nodejs

复制代码
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', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');if (req.method === 'OPTIONS') {res.sendStatus(204);} else {next();}});
服务端语言 / 框架 配置方式示例
Node.js(Express) ```javascript
const express = require('express');
const app = express();

Preflight意义

CORS 预检请求(Preflight)失败 ,具体错误类型是 HeaderDisallowedByPreflightResponse

其本质原因是:前端发起跨域请求时,浏览器发送的预检(OPTIONS)请求中包含了自定义 HTTP 头,但 PHP 后端的响应头中未配置允许这些自定义头

阿雪技术观

让我们积极投身于技术共享的浪潮中,不仅仅是作为受益者,更要成为贡献者。无论是分享自己的代码、撰写技术博客,还是参与开源项目的维护和改进,每一个小小的举动都可能成为推动技术进步的巨大力量

Embrace open source and sharing, witness the miracle of technological progress, and enjoy the happy times of humanity! Let's actively join the wave of technology sharing. Not only as beneficiaries, but also as contributors. Whether sharing our own code, writing technical blogs, or participating in the maintenance and improvement of open source projects, every small action may become a huge force driving technological progrss

相关推荐
见闻小天地28 分钟前
从晶片工艺到可靠性验证:晶威特TF-3215型RTC晶振全面解析
运维·业界资讯
沸速存储1 小时前
AI 机器人靠哪些内存与存储驱动整机运行?
服务器·科技·嵌入式硬件·电脑
名字还没想好☜2 小时前
Docker 网络实战:bridge/host/none/自定义网络、容器互通与端口映射踩坑
运维·docker·kubernetes
fengyehongWorld2 小时前
Linux squid搭建基础代理服务器
linux·运维·服务器
木白CPP2 小时前
Linux DMA驱动详解(二)-----DMA的使用者
java·linux·运维
赵民勇2 小时前
systemd-socket-activate命令详解
linux·运维
跨境小彭3 小时前
Temu运营避坑:制造地点信息填写规范、后果及批量实操教程
大数据·运维·自动化·跨境电商·temu
Cx330❀3 小时前
【Linux网络】网络层 IP 协议:从网段划分到内核源码解析
大数据·linux·服务器·网络·tcp/ip·性能优化·langchain
Dachui_11223 小时前
ZeroNews LFS 使用教程:NAS 文件发布为公网 HTTPS 文件空间,不传网盘、按人授权、免登录分享
运维·网络安全·文件共享·团队协作·nas
智能运维指南4 小时前
2026年企业自动化运维平台选型:四类架构的差异与决策逻辑
运维·人工智能·嘉为蓝鲸