在服务器端实现跨域资源共享(CORS)需要通过配置HTTP响应头来允许不同源的客户端访问资源,以下是常见服务器环境的配置方法:

核心原理
在响应头中添加以下字段:
Access-Control-Allow-Origin: 允许的域名(或 * 表示所有域名) Access-Control-Allow-Methods: 允许的HTTP方法(如 GET, POST, PUT) Access-Control-Allow-Headers: 允许的请求头(如 Content-Type, Authorization) Access-Control-Allow-Credentials: true(如需传递Cookie) Access-Control-Max-Age: 预检请求缓存时间(秒)
具体配置示例
Nginx 配置
server {
listen 80;
server_name yourdomain.com;
location / {
# 基础跨域设置
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
# 预检请求处理
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
}
}
Apache 配置 (.htaccess)
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type, Authorization"
# 处理OPTIONS预检请求
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>
Node.js (Express)
const express = require('express');
const app = express();
// 中间件设置CORS
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'); // 或指定域名如 'https://client.com'
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// 处理预检请求
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
app.listen(3000);
Spring Boot (Java)
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*") // 或具体域名
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(false)
.maxAge(3600);
}
}
Python Flask
from flask import Flask
from flask_cors import CORS # 安装: pip install flask-cors
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}}) # 全局允许所有域名
# 或精细控制
@app.after_request
def add_cors_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
response.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,DELETE'
return response
ASP.NET Core
public void ConfigureServices(IServiceCollection services) {
services.AddCors(options => {
options.AddPolicy("AllowAll", builder => {
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
}
public void Configure(IApplicationBuilder app) {
app.UseCors("AllowAll"); // 应用策略
}
关键注意事项
-
安全性:
- 避免滥用
Access-Control-Allow-Origin: *,推荐指定具体域名。 - 如需传递Cookie,设置
Access-Control-Allow-Credentials: true并明确指定域名(不能为 )。
- 避免滥用
-
预检请求 (OPTIONS):

- 复杂请求(如自定义Header、非简单方法)会先发送OPTIONS请求。
- 确保服务器正确处理OPTIONS并返回204/200。
-
缓存优化:
- 使用
Access-Control-Max-Age减少预检请求次数。
- 使用
-
Vary 头:
- 当根据请求头动态返回内容时,添加
Vary: Origin防止缓存问题。
- 当根据请求头动态返回内容时,添加
测试工具
- 浏览器开发者工具(Network标签查看请求头/响应头)
curl命令测试:curl -I -X OPTIONS http://yourserver.com/api -H 'Origin: http://client.com'
通过以上配置,服务器即可安全、有效地支持跨域请求,根据实际场景调整域名、方法和头域限制,平衡功能与安全性。

图片来源于AI模型,如侵权请联系管理员。作者:酷小编,如若转载,请注明出处:https://www.kufanyun.com/ask/284342.html

