使用 Nginx 代理转发解决 Weex 本地 H5 调试的跨域问题

更新日期: 2017-06-20 阅读次数: 10378 分类: Nginx

使用 Weex 开发 APP, 有一个坑,就是如果使用浏览器进行接口调试,会遇到 js 的跨域问题。 虽然,APP 上不会有此问题,但是严重影响了调试。

例如,本地 H5 调试页面,报错

XMLHttpRequest cannot load http://x.x.x.x:8080/services/zhongweiService. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:1337' is therefore not allowed access.
stream.js:116 [h5-render] unexpected error in _xhr for 'fetch' API

为了不影响现有服务器的环境配置, 使用 Nginx 做代理转发

server {
	listen 10000;

	server_name localhost;

	location / {
		add_header 'Access-Control-Allow-Origin' '*';
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header X-NginX-Proxy true;
		proxy_pass http://x.x.x.x:8080/services/zhongweiService;
		proxy_ssl_session_reuse off;
		proxy_set_header Host $http_host;
		proxy_redirect off;
	}

}

即在,返回的 HTTP 头上缀上

'Access-Control-Allow-Origin' '*';

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式