uni-app H5跨域问题java设置Access-Control-Allow-Origin

  • 内容
  • 相关
首先在后台项目中加一个CORSFilter类:
package cn.yygzs.modules.cemetery.utils;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CORSFilter implements Filter{
	 	@Override
	    public void init(FilterConfig filterConfig) throws ServletException {
	 
	    }
	 
	    @SuppressWarnings("rawtypes")
		@Override
	    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
	        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
	        // 如果不是80端口,需要将端口加上,如果是集群,则用Nginx的地址,同理不是80端口要加上端口  
			String []  allowDomain= {"http://yykj-localhost.natapp1.cc","http://localhost:8081","http://127.0.0.1:8080"};
			@SuppressWarnings("unchecked")
			Set allowedOrigins= new HashSet(Arrays.asList(allowDomain));
			String originHeader=((HttpServletRequest) servletRequest).getHeader("Origin");
			if (allowedOrigins.contains(originHeader)){
				httpResponse.setHeader("Access-Control-Allow-Origin", originHeader);
				httpResponse.setContentType("application/json;charset=UTF-8");
				httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
				httpResponse.setHeader("Access-Control-Max-Age", "3600");
				httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
				// 如果要把Cookie发到服务器,需要指定Access-Control-Allow-Credentials字段为true
				httpResponse.setHeader("Access-Control-Allow-Credentials", "true");                                
				httpResponse.setHeader("Access-Control-Expose-Headers", "*");        
			} 
			System.err.println("进入请求================================");
			filterChain.doFilter(servletRequest, servletResponse);
	    }
	 
	    @Override
	    public void destroy() {
	    	System.out.println("ceshi");
	    }

}

然后在web.xml中添加

<!-- 请求头设置开始 -->
  	<filter>
	    <filter-name>CorsFilter</filter-name>
	    <filter-class>cn.yygzs.modules.cemetery.utils.CORSFilter</filter-class>
	</filter>
	 
	<filter-mapping>
	    <filter-name>CorsFilter</filter-name>
	    <url-pattern>/*</url-pattern>
	</filter-mapping>
  <!-- 结束 -->

 

然后重启项目就行,搞定!

本文标签:

版权声明:若无特殊注明,本文皆为《悟性》原创,转载请保留文章出处。

本文链接:uni-app H5跨域问题java设置Access-Control-Allow-Origin - https://yygzs.org/?post=23

发表评论

电子邮件地址不会被公开。 必填项已用*标注

未显示?请点击刷新

Sitemap