- 一、什么是跨域
- 二、Nginx 端口配置
当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。
| 当前页面url | 被请求页面url | 是否跨域 | 原因 |
|---|---|---|---|
| http://www.test.com/ | http://www.test.com/index.html | 否 | 同源(协议、域名、端口号相同) |
| http://www.test.com/ | https://www.test.com/index.html | 跨域 | 协议不同 |
| http://www.test.com/ | http://www.baidu.com/ | 跨域 | 主域名不同(test/baidu) |
| http://www.test.com/ | http://blog.test.com/ | 跨域 | 子域名不同(www/blog) |
| http://www.test.com:8080/ | http://www.test.com:7001/ | 跨域 | 端口号不同(8080/7001) |
2.1 nginx 配置
server {
listen 7777;
server_name localhost;
location / {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass "http://localhost:8002";
}
location /rs/ {
proxy_pass "http://localhost:8888";
index index.html index.htm index.jsp;
}
}
2.2 Flutter web 启动端口设置
flutter run -d chrome --web-port 8002 --web-hostname 127.0.0.1
2.3 Server 接口示例
2.3.1 Flutter 中使用代理地址
http://127.0.0.1:7777/rs/addconfig
2.3.2 Server API 实际地址
http://127.0.0.1:8888/rs/addconfig
2.4 操作步骤
- Flutter 项目使用固定端口启动(如2.2所示),此时Flutter项目部署在8002端口。
- 启动后修改链接为http://127.0.0.1:7777/#/访问,此时需要restart 项目生效。
- Dart 中Server 接口改为2.3.1所示,此时前后端访问的ip:host一致,成功解决跨域问题。



