一、背景:
前后端分离,前端:vue3,后端:flask
前端打包合并到后端后,需要将该项目部署到正式服务器,并为其配置域名。配置完成后,却出现了http能访问,https无法访问的问题,报错如下:
Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://...'. This request has been blocked; the content must be served over HTTPS.

二、尝试
碰到这个问题的人不少,但是解决方法都类似,都是通过某种方法将http请求强制转成https请求。
第一种:
在页面中加入如下<meta>标签
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
第二种:
nginx配置如下语句
add_header Content-Security-Policy "upgrade-insecure-requests;connect-src *"
这两种方法我都尝试过了,它们的结果是一致的,但是并不理想,没有解决我的问题。通过这两种方法,我得到的结果是https可以访问了,但是http访问时又出现了另外的问题。
三、解决方案
最后,我终于找到了问题的真正所在。是因为前端请求后缺少斜杠。即将下面的请求url
url: '/api/get_data
改为如下url
url: '/api/get_data/
是的,就是这么愚蠢,就是这么简单。
参考:https://www.it1352.com/202186.html
I just spent a good 4 hours trying to fix a similar problem. Here's what solved mine:
Summary: add a trailing '/' to your request
I found this post useful in fixing my problem. Basically, the server doesn't care if you send your request with a trailing '/' or not, because it internally routes to '/' if you don't add it. However, if the routing is happening internally (e.g. nginx passing the request to a local process), you get an http redirect which will make your request fail.
四、 结束语
记录学习之旅,与君共勉
在部署前后端分离的Vue3+Flask项目时,配置nginx后发现http能正常访问,但https出现错误。错误提示为 Mixed Content,尝试通过设置meta标签和nginx的Content-Security-Policy未解决问题。最终发现,问题在于前端请求URL缺少斜杠,添加斜杠后解决了https访问问题。

1698

被折叠的 条评论
为什么被折叠?



