0
我有這樣的服務,我在我的本地機器上公佈:配置http請求spring mvc和angular js?
http://joediego.dtdns.net:3000/jcsistemas/rest/cliente/all
如果我打afromentioned URL終點,我可以讓我的JSON提要響應。但是當我使用另一個主機名,如http://localhost:8081,服務與以下消息響應:
XMLHttpRequest can not load http: // localhost: 8081/jcsistemas/rest/customer/all. In the 'Access-Control-Allow-Origin "header is present on the requested resource. Origin 'http: // localhost: 9000' is not allowed Therefore access.
這裏是我試過至今克服了同源策略的問題:
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.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
//filter
@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() {}
}
@Configuration
@EnableWebMvc
@ComponentScan("my..package...... ")
public class WebAppConfig extends WebMvcConfigurerAdapter {
//configureContentNegotiation
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true).
ignoreAcceptHeader(true).
useJaf(false).
defaultContentType(MediaType.APPLICATION_JSON).
mediaType("html", MediaType.TEXT_HTML).
mediaType("xml", MediaType.APPLICATION_XML);
}
}
AngualarJS模塊配置:
angular.module('my_module').config(['$routeProvider','$httpProvider',function($routeProvider,$httpProvider) {
//how configure headers here??
}]);
}());