NutzCN Logo
问答 ajax请求跨域 携带cookie问题
发布于 253天前 作者 qq_ca9d2523 495 次浏览 复制 上一个帖子 下一个帖子
标签:

ajax代码

$.ajax({
			xhrFields: {
	            withCredentials: true
	        },
	        crossDomain: true,
			type:"get",
			url: "http://127.0.0.1:8080/test/user/menus",
			success: function(result) {
				console.log(result);
			}
		});

java设置
入库函数添加@Filters(@By(type = MyCrossOriginFilter.class))

public class MyCrossOriginFilter implements ActionFilter {
    private static final Log log = Logs.get();

    protected String origin;
    protected String methods;
    protected String headers;
    protected String credentials;

    public ShopCrossOriginFilter() {
        this("null",
             "get, post, put, delete, options",
             "origin, content-type, accept",
             "true");
    }

    public ShopCrossOriginFilter(String origin,
                                 String methods,
                                 String headers,
                                 String credentials) {
        this.origin = origin;
        this.methods = methods;
        this.headers = headers;
        this.credentials = credentials;
    }

    public View match(ActionContext ac) {
        HttpServletResponse resp = ac.getResponse();
        HttpServletRequest request = ac.getRequest();
        System.err.println(request.getHeader("Credentials"));

        if (!Strings.isBlank(origin))
            resp.setHeader("Access-Control-Allow-Origin", origin);
        if (!Strings.isBlank(methods))
            resp.setHeader("Access-Control-Allow-Methods", methods);
        if (!Strings.isBlank(headers))
            resp.setHeader("Access-Control-Allow-Headers", headers);
        if (!Strings.isBlank(credentials)) {
            resp.setHeader("Access-Control-Allow-Credentials", credentials);
        }

        if ("OPTIONS".equals(ac.getRequest().getMethod())) {
            if (log.isDebugEnabled())
                log.debugf("Feedback -- [%s] [%s] [%s] [%s]",
                           origin,
                           methods,
                           headers,
                           credentials);
            return new VoidView();
        }
        return null;
    }
}

报错信息

XMLHttpRequest cannot load http://127.0.0.1:8080/test/user/menus. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://127.0.0.1:8020' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
1 回复

加上 Access-Control-Allow-Origin

"origin, content-type, accept, Access-Control-Allow-Origin",

添加回复
请先登陆
回到顶部