Nginx前端跨域

假设:
前端路径:http://127.0.0.1:8081
请求路径:http://192.168.11.124:111

解决:
前端请求接口设为:(加上api、后面为真正请求路径)
http://127.0.0.1:8081/api/xxx
则请求会被转发到http://192.168.11.124:111/xxx

nginx.conf:

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    
    server {
        listen       8080;
        server_name  127.0.0.1 localhost;
        location /{
	        proxy_pass http://127.0.0.1:8081;
	    }
        location /api{
	       # add_header Access-Control-Allow-Origin *;
	       # add_header Access-Control-Allow-Methods 'GET,POST,OPTIONS';
	       # add_header Access-Control-Allow-Headers '*';
	       # if ($request_method = 'OPTIONS'){
	       #     return 204;
	       # }
	        proxy_pass http://192.168.11.124:111;
	    }
    }
}

使用live-server监听8081端口
nginx监听了8080端口

最后访问127.0.0.1:8080(nginx设置的端口) 就可实现跨域

        location /api/{
	        proxy_pass http://192.168.11.118:8080/;
	    }
        location /{
	        proxy_pass http://127.0.0.1:8777;
	    }
posted @ 2021-04-19 16:27  爬塔游戏  阅读(93)  评论(0)    收藏  举报