所以到现在都没有解决方案么。。
update
我解决了。后端是Java springboot,前端是angular,跨域json通信。
cors方式,配置一个corsfilter,代码如下:
package xxxxxx.component;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by skyADMIN on 16/7/4.
*/
@Component
public class CORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("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");
response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
这个配置在不少地方应该都能找到,不同的主要是两点:
1。response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
2。response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
首先,配置了allow-credentials之后,如果allow-origin设为*,跨域时会报错说因为允许credentials,origin不能设为通配*,那所以设为简单的某个domain也是可以的,这种写法应该就是达到了任意domain都可以的效果吧。
然后angular部分也要设定个东西,举个栗子~
angular.module('frontendApp')
.controller('MainCtrl', function ($scope, $http, $location) {
var action = 'islogin';
$http.get(apiUrl + action, {withCredentials: true}).then(function (response) {
console.log(response);
if (response.data === 0) {
$location.url('login');
}
})
});
恩就是这个$http.get(url, {withCredentials: true})。
ok就酱。