环境
Debian12
192.168.2.102/24
rambo@mac:~$ cat /etc/apt/sources.list.d/debian.sources
Types: deb
URIs: https://mirrors.tuna.tsinghua.edu.cn/debian
Suites: bookworm bookworm-updates bookworm-backports
Components: main contrib non-free non-free-firmware
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg
配置前端服务器 (端口3000)
rambo@mac:~$ sudo apt install -y nginx
rambo@mac:~$ sudo nginx -v
nginx version: nginx/1.22.1
rambo@mac:~$ sudo vim /etc/nginx/sites-available/frontend
server {
listen 3000;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
rambo@mac:~$ sudo vim /var/www/html/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CORS Issue</title>
</head>
<body>
<h1>CORS Issue Example</h1>
<button id="fetchData">Fetch Data</button>
<script>
document.getElementById("fetchData").addEventListener("click", () => {
fetch("http://192.168.2.102:5000/api/data", {
method: "GET",
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
});
</script>
</body>
</html>
配置API服务器 (端口5000)
rambo@mac:~$ sudo vim /etc/nginx/sites-available/api
server {
listen 5000;
location /api/ {
default_type application/json;
# 不设置 CORS(复现问题)
add_header Access-Control-Allow-Origin ""; # 为空,不允许跨域
return 200 '{"message": "Hello from the API server!"}';
}
}
启用配置
sudo ln -s /etc/nginx/sites-available/frontend /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/api /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
rambo@mac:~$ cat /etc/nginx/sites-available/api
server {
listen 5000;
location /api/ {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
add_header Access-Control-Allow-Headers "Content-Type";
default_type application/json;
return 200 '{"message": "Hello from the API server!"}';
}
}
rambo@mac:~$ sudo systemctl reload nginx