彻底解决uniapp发布为H5的跨域问题

一, uniapp发布成网站-PC Web或手机H5跨域

用HBuilder开发时, 用内置浏览器预览没有跨域的问题, 当发布为H5时, 调用后台接口就会出现跨域问题,如下图
在这里插入图片描述

二, 什么是跨域?

当一个请求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/https)
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)

三, nginx解决跨域

在一个server内配置多个location,转发前后端的请求
具体配置如下图:

1,前端项目请求的后端地址改成nginx所在服务器的IP和监听的端口号
在这里插入图片描述

2,发布成H5之后,放到如下位置
发布成H5之后,放到如下位置

3,修改nginx的配置文件


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    
    #access_log  logs/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  100;
    #gzip  on;

    server {
		listen 8090;# 监听的端口号
	    server_name localhost;# 域名
	    #index index.php index.html index.htm default.php default.htm default.html;
	    gzip on;
	    gzip_static on;     # 需要http_gzip_static_module 模块
	    gzip_min_length 1k;
	    gzip_comp_level 4;
	    gzip_proxied any;
	    gzip_types text/plain text/xml text/css;
	    gzip_vary on;
	    gzip_disable "MSIE [1-6]\.(?!.*SV1)";
    
    
    # 后端接口地址 若新增后端路由前缀注意在此处添加(|新增)
    location / {
	   proxy_pass http://192.168.1.911:9999/;# 网关地址
       proxy_connect_timeout 60s;
       proxy_send_timeout 60s;
       proxy_read_timeout 60s;
       #proxy_set_header X-Real-IP $remote_addr;
       #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       #proxy_set_header X-Forwarded-Proto http;
    }
	
	#location ~* .*\.(js|css|ico|png|jpg|eot|svg|ttf|woff|html|txt|pdf){
	#   alias D:/Tools/nginx-1.12.2/html/creatar/;
	#   expires 30d;
	#}
	
    #前端页面地址
	location /creatar/ {
	   alias D:/Tools/nginx-1.12.2/html/creatar/;
	   #expires 30d;
	}
	
    # 避免端点安全问题
    if ($request_uri ~ "/actuator"){
        return 403;
    }
    }
}

4,浏览器访问
地址栏输入 nginx服务器的IP+监听端口号+页面的地址
在这里插入图片描述
在这里插入图片描述
OK,打完收工!!

方法不止这一种, 如有不正,望不吝赐教~~~

  • 10
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值