在请求时,f12提示POST请求报错405

nginx转发至后端nginx,后端nginx转发至后端golang api接口
根据网上方法排查,发现80%以上无非就是以下几个解决方法
方法一:将所有POST 405错误发送到命名位置@app 资料地址:https://distinctplace.com/2017/04/17/405-not-allowed-nginx-fix-post-requests/
server {
listen 80;
root /my/root;
error_page 405 = $uri;
# magic happens here
rewrite ^.*$ /api.json last;
location / {
index index.html;
}
}
方法2:error_page 405 =200 $uri;
server {
listen 80
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 404 /404.html;
error_page 403 /403.html;
# To allow POST on static pages 允许静态页使用POST方法
error_page 405 =200 $uri;
}
还有的网站上写明说需要重新编译nginx,如:https://gist.github.com/zxhfighter/7560812
此种方式经过尝试后,发现问题,查询资料后说明error_page 405 =200 $uri;是将将POST请求转换为GET。https://stackoverflow.com/questions/24415376/post-request-not-allowed-405-not-allowed-nginx-even-with-headers-included
而使用此方法会出现返回不一致的问题,如这里应返回json文本,此处却是 html的文本,其原因就是因为请求的方式不一致,因返回格式不一致,导致前端报错。

此时尝试其他方法进行解决,将nginx转发配置更改为如下配置
location / {
proxy_pass http://log.xxxx.xxxx.com:81/;
proxy_set_header Host $host;
client_max_body_size 10m;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
之前的配置如下
location /xxx/ {
proxy_pass http://log.xxxx.xxxx.com:81/;
}
这时出现502问题,查看后端nginx发现并无前端的请求,并且后端服务没有问题。使用proxy_pass 中填写的地址用postman模拟是可以正常访问。

经过排查发现,问题的原因是在于 nginx中传递了host,而后端也是nginx反向代理,而此nginx中并无原始请求的host,故报502错误。
proxy_set_header Host $host;
删除Host的设置,成功返回200,但是有一个问题为,并无返回值。

检查nginx配置,发现nginx代理时使用这种方式时没有传递请求参数的,故没有返回值。 备注:nginx如何转发参数,参考的此篇文章https://codeday.me/bug/20170920/74504.html
location / {
proxy_pass http://log.xxxx.xxxx.com:81/;
proxy_set_header Host $host;
client_max_body_size 10m;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
修改后配置
location ~* ^/xxxxx/(.*)$ {
proxy_pass http://logs.xxx.xxxxx.com:81/$1;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
修改完成后,再次访问,发现请求变成GET,查询nginx官网文档,http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_method。文档中提到,此时的请求不是客户端的请求,而是反向代理客户端的请求,可以用proxy_method POST;设置请求方式为POST。
最终配置文件如下
location ~* ^/xxxxx/(.*)$ {
proxy_pass http://logs.xxxx.xxxxxxxxxx:81/$1;
proxy_method POST;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
此时,请求正常了

原文:https://www.cnblogs.com/LC161616/p/10371761.html