跨域---一个经典话题
跨域—(admin模板里的网络请求是什么样的)
-
url = url = base url + request url
-
env.development 下(对应开发环境下, 其他环境在其他的env.xxxx文件中配置):
VUE_APP_BASE_API = '/api' -
api/sysUser.js下:
....url: "/SysUserInfo/pageQuery",...那么现在, 请求地址就是/api/SysUserInfo/pageQuery -
我们会有我们的后端服务, 运行在其他地址(服务器中), 这就需要设置代理
-
vue.config.js中:
devServer: { port: port, open: true, proxy: { "/api": { target: "http://101.37.39.228:9162", } } },其中, 关键部分就是
proxy, 里面的target就是后端的服务地址这样设置后, 请求到
/api/SysUserInfo/pageQuery, 会被代理到请求:http://101.37.39.228:9162/api/SysUserInfo/pageQuery
-
-
vue.config.js中设置的代理在打包到生产环境后并不能生效, 这时就需要
nginx来设置网络代理. (同样是设置代理, vue.config.js是在本地启动一个服务器来将请求代理到目标服务器, nginx是通过服务器来代理请求, 前端向自己的服务器发起请求, 服务器再把请求代理带目标服务器, 这样就一劳永逸地解决了跨域问题)-
nginx配置案例:
server { listen 3333; server_name localhost; # compression-webpack-plugin 配置 # 配置支持gz压缩 gzip on; gzip_min_length 1k; gzip_comp_level 9; gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; gzip_vary on; # 配置禁用 gzip 条件,支持正则,此处表示 ie6 及以下不启用 gzip(因为ie低版本不支持) gzip_disable "MSIE [1-6]\."; #charset koi8-r; #access_log logs/host.access.log main; #前端打包后部署位置 location / { root C:\Users\Administrator\Desktop\vue-project\watch\dist; try_files $uri $uri/ @router; index index.html index.htm; } location /api { #代理的目标地址 proxy_pass http://101.37.39.228:9162; proxy_connect_timeout 600; proxy_read_timeout 600; } location @router { rewrite ^.*$ /index.html last; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
-