前端代码中如何避免暴露后端接口

在日常开发中,后端同事会给前端一个地址,这个地址我们不想暴露出来,具体操作该怎么做?

这里已vue3 的项目为例子。react 原理是一样的

第一步前端配置

    .env.production文件
VUE_APP_NODE_ENV = "production"

# base api
VUE_APP_BASE_API = /  // 这里这单纯的设置为/, 这样程序自动获取前端的host

解释: 前端的访问地址为: http://www.hhhh.com, 接口地址:http://api.hhhh.com/api/hotel/list

这里我们希望用户只能看到http://www.hhhh.com/api/hotel/list, 这样后端接口就被隐藏起来了

第二步nginx配置

server {
        listen       80;
        server_name  www.hhhh.com;
        #charset koi8-r;

        #access_log  logs/host.access.lsog  main;

	location / {

		#设置主机头和客户端真实地址,以便服务器获取客户端真实IP
		proxy_set_header Host $host;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		#禁用缓存
		proxy_buffering off; 

		#反向代理的地址
		proxy_pass http://127.0.0.1:1122;

		root /workspace/inTravel/h5;
		index index.html index.htm; 
		try_files $uri $uri/ /index.html; 

	}

	location /api {
		proxy_pass http://api.hhhh.com;
	}
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

当nginx 匹配到路由时候, location /api 时候,自动代理到 api的接口


我的开源作品: 欢迎吐槽

经验分享 程序员 微信小程序 职场和发展