廣告

2015年6月15日 星期一

XMLHttpRequest cannot load URL 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

ws為spring+restful
前端為html+ajax

新增下列程式
package com.cihm.controller;
import java.io.IOException;
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.HttpServletResponse;
import org.springframework.stereotype.Component;

@Component
public class SimpleCORSFilter implements Filter {

 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
  HttpServletResponse response = (HttpServletResponse) res;
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
  response.setHeader("Access-Control-Max-Age", "3600");
  response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
  chain.doFilter(req, res);
 }

 public void init(FilterConfig filterConfig) {}

 public void destroy() {}

}


web.xml添加
 
       SimpleCORSFilter
       
        com.cihm.controller.SimpleCORSFilter
       
     
     
    
    SimpleCORSFilter
    /*
    


參考https://spring.io/guides/gs/rest-service-cors/

沒有留言:

張貼留言