CORS & example.com

前端 未结 3 1104
刺人心
刺人心 2021-01-29 14:33

I have a trouble with CORS. I use an API which has

Access-Control-Allow-Origin: http://www.example.com

Because of that, I can\'t access the i

3条回答
  •  遇见更好的自我
    2021-01-29 15:34

    if you are accessing the other origin(host) from your origin then you will not access the api in ajax call because other origin will have been disallow the access of another host. So to access the api you need to allow the particular path pattern on server side which you want to access.

    web.xml file in java project.

    
      
         myFilter
         CorsFilter
      
      
         myFilter
         /rest/*
      
      
         myRestPath
         com.MyServlet
      
      
         /rest/*
         myRestPath
      
    
    

    You can edit your login in MyFilter.java file or you can also add the init parameter in web.xml file.

    MyFilter.java

    public class CorsFilter implements Filter{
    
     @Override
     public void init(FilterConfig fConfig) throws ServletException {
        // do something
      }
    
     @Override
     public void doFilter(ServletRequest request, ServletResponse response, 
     FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) request;
        HttpServletResponse response = (HttpServletResponse) response;
    
        //here * is used to allow all the origin i.e. anyone can access the api
        response.addHeader("Access-Control-Allow-Origin", "*");
    
        // methods which is allowable from the filter
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS,PUT, DELETE, HEAD");
    
        //custom header entry
        response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
        filterChain.doFilter(request, response);
     }
    
     @Override
     public void destroy() {
       //do something
     }
    
     }
    

    I think it will be right solution for your query.

提交回复
热议问题