ajax跨域方法 阳光穿透心脏的1/2处 2022-07-14 00:30 153阅读 0赞 ## **nginx url rewrite** ## 在服务器端安装nginx服务,将H5前端的访问路径和java后端的访问路径放在一个域名下,由nginx根据url请求路径进行转发: [http://aaa.afubx.com/afbx-wap][http_aaa.afubx.com_afbx-wap] ==》 afbx-wap [http://aaa.afubx.com/afbx-rest][http_aaa.afubx.com_afbx-rest] ==> afbx-rest Nginx配置: server \{ listen 80; server\_name aaa.afubx.com; index index.html index.htm; location /afbx-rest \{ \#proxy\_redirect off; 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\_pass http://192.168.0.202:18081; \} location /afbx-wap/afbx-wap \{ index index.php index.html index.htm; rewrite "/afbx-wap/(.\*)" /$1; \} location /afbx-wap \{ \#proxy\_redirect off; 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\_pass http://192.168.0.202:18083; \} \} 优点:通过同一域访问,不存在跨域问题。 缺点:需要安装配置nginx,并且存在nginx单点压力的隐患。 ## **跨域资源共享CROS** ## 服务端根据http请求头的Origin字段进行判断,设置允许访问的域名访问。 解决方法: 服务端拦截请求,通过HttpServletRequest.getHeader(“Origin”)进行判断,如果是白名单就设置HttpServletResponse.setHeader(“Access-Control-Allow-Origin”,”\{ 来源域名\}”); Java代码: List whiteList = new ArrayList(); whiteList.add(“”); String filterDrive = “wap”; HttpServletResponse res = (HttpServletResponse) message.get(AbstractHTTPDestination.HTTP\_RESPONSE); HttpServletRequest req = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP\_REQUEST); If(filterDrive.equas(req.getParameter(“drive”)))\{ String origin = req.getHeader("Origin"); If(whiteList.contains(origin))\{ res.setHeader("Access-Control-Allow-Origin", origin); \} \} 优点:使用ajax直接跨域访问,服务端添加支持,对以前的代码无影响。 缺点: ## ** ** ## [http_aaa.afubx.com_afbx-wap]: http://aaa.afubx.com/afbx-wap [http_aaa.afubx.com_afbx-rest]: http://aaa.afubx.com/afbx-rest
还没有评论,来说两句吧...