快速解决前后端跨域问题 - Tinywan
source link: https://www.cnblogs.com/tinywan/p/16057923.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
快速解决前后端跨域问题
跨域和同源策略
需求
最近使用一个golang的前后端项目,本地运行老是跨域
1、前端地址:http://192.168.3.12:8888/
2、后端地址:http://192.168.3.12:8000/
可以明显看出是不同的端口,协议都是localhost没啥问题
解决方案
使用nginx解决,配置一个虚拟server。命名为:sky.tinywan.cn.conf
server {
server_name sky.tinywan.cn;
# 代理前端
location / {
proxy_pass http:
//192.168.3.12:8888;
}
# 代理后端
location /apis/ {
add_header Access-Control-Allow-Origin
'*'
;
add_header Access-Control-Allow-Methods
'GET, PUT, POST, DELETE, OPTIONS'
;
add_header Access-Control-Allow-Headers
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
;
if
(
$request_method
=
'OPTIONS'
) {
return
204;
}
proxy_pass http:
//192.168.3.12:8000;
}
}
上面由于使用Docker,所以直接是使用的宿主机的ip地址 192.168.3.12
修改以下本地的hosts(路径:C:\Windows\System32\drivers\etc)文件,添加以下内容
127.0.0.1 sky.tinywan.cn
配置好后,重启nginx
修改前端本地环境配置 .env.development
# 本地环境
ENV =
'development'
# 本地环境接口地址
VITE_API_URL =
'http://sky.tinywan.cn/apis'
这时候直接通过域名访问
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK