部署前端时OpenResty配置问题
type
status
date
slug
summary
tags
category
icon
password
😀
胡萝卜部署了一个前端的项目,本地可以运行调用api.**.cn的后端接口,但是放到浏览器或者放到Vercel上就不能进行调用了。

问题出现

项目最初只在小程序上部署了接口,那时后端没有考虑跨域的问题。然而,随着管理后台的上线,问题变得明显起来:
  • 前端域名:a.**.cn
  • 后端域名:api.**.cn
一开始还是开了前端cros跨域,但是调用的时候是a.**.cn/api/**,出现了502 gateway, 网关找不到服务器。以为是生产环境只能这样配置,于是把前端部署到了api.**.cn/api/上,但以上问题还是出现,看来生产环境不能用前端跨域解决问题。

解决方案的转变

于是,关闭了前端的CORS跨域设置,并将接口地址直接更改为api.**.cn。然而,这次遇到了403 Forbidden的问题:
request URL: https://api.**.cn/groups/loginManagement Request Method: OPTIONS Status Code: 403 Forbidden
这时候已经查阅了一些资料,将openresty的配置如下
location ^~ / { proxy_pass http://127.0.0.1:8585; proxy_set_header Host $host; add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; add_header Access-Control-Allow-Credentials true; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_http_version 1.1; add_header Cache-Control no-cache; }
看了很多资料,最主要的原因还是各种请求并没有转发出去,于是问了GPT
给出解释如下:
你的跨域设置需要在所有响应中都生效,而不仅仅是在OPTIONS请求中。你可以添加 if ($request_method = 'OPTIONS') 条件来确保这些设置在OPTIONS请求中生效。
if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; add_header Access-Control-Allow-Credentials true; add_header Access-Control-Allow-Headers $http_access_control_request_headers; add_header Content-Type 'text/plain charset=UTF-8'; add_header Content-Length 0; return 204; }
最终成功跨域调用了接口,但以后还是记得刚开始就在后端配置跨域吧😅。

新的问题

后台管理页面启动后,虽然可以正常调用接口了,但是新的问题出现了,只要在非主页的地方刷新页面,就会出现404 not found
推测是前端部署的项目只含有index主页面,当刷新的时候主页找不到别/XXX路由界面。因为并没有其他页面的资源文件。

解决方法

只需要把这行代码加到我们的根目录的location配置项中就可以解决这个问题
try_files $uri $uri/ /index.html;

参考文章

 


开往-友链接力