我有一个由nginx服务的角度应用程序,这个有角度的应用程序与同一服务器上的休息后端进行通信.
我在/ etc / nginx / sites-available /中有以下两个服务器配置
“默认”和“应用”
默认服务器在80上监听时,Angular应用程序正在正确提供.
server{
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.html ;
}
}
然后在我的“app”服务器块中,它应该重定向休息后端的请求,
server{
listen [::]:80 ;
server_name xxx.com;
location / {
proxy_pass http://127.0.0.1:8082;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
但是当我的角度应用程序命中POST API端点时,它会获得405(方法不允许),这是因为它直接命中nginx服务器甚至没有进入休息端点(8082),否则将首先发送OPTIONS,但我看到只有一个请求和POST直接请求,这意味着它甚至没有重定向到其他端口,否则将在我的REST后端调用CORS设置.
我不知道我做错了什么,同样的应用程序在本地工作得很好.
我已经仔细检查了启用站点的文件夹中的符号链接,它们是绝对路径.
编辑:
我的请求标题
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.9
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:example.com
Origin:http://example.com
Pragma:no-cache
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
我的Os
Ubuntu:16.04,
nginx:1.10.3.
最佳答案 尝试合并两个服务器块:
server{
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.html ;
}
location /api/ {
proxy_pass http://127.0.0.1:8082/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
并通过在网址中附加’/ api /’来访问所有其他api.
可能是它的CORS问题,在您的位置块中添加:
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}