ajax – Spring MVC Zepto POST中的“Access-Control-Allow-Origin”错误

前端之家收集整理的这篇文章主要介绍了ajax – Spring MVC Zepto POST中的“Access-Control-Allow-Origin”错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将JSON对象POST到我的Spring MVC控制器,但我只收到Access-Control-Allow-Origin错误. @H_403_1@我的控制器:

@RequestMapping(value= "/add",method = RequestMethod.POST,headers = {"content-type=application/json"})
public @ResponseBody Reponse addUser(Model model,@RequestBody @Valid @modelattribute("user") User user,BindingResult result) {
    if (result.hasErrors()) {
        Reponse error = new Reponse();
        // etc......
        return error;
    } else {
        return service.addUser(user);
    }
}
@H_403_1@我的Zepto POST:

this.addUser = function (valeur,callback) {
    $.ajax({
        type: 'POST',url: 'http://127.0.0.1:8080/AgenceVoyage/user/add',data: JSON.stringify({"mail" : "toto@toto.fr","password" : "titi"}),dataType: "json",contentType: "application/json",success: function(data) {
            if(data.reponse == "OK") {
                window.location = "main.html";
            } else {
                alert("PROBLEM");
            }
        },error: function(xhr,type) {
            alert("ERROR");
        }
    });
};
@H_403_1@我尝试在POST请求中没有stringify,在@RequestMapping中没有标题.

@H_403_1@我的结果:

@H_403_1@OPTIONS 07000 No
‘Access-Control-Allow-Origin’ header is present on the requested
resource. Origin ‘07001’ is therefore not allowed
access. zepto.min.js:2 XMLHttpRequest cannot load

我找到了解决方案: @H_403_1@首先,创建一个新的过滤器,它将设置标头响应:

@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() {}

}
@H_403_1@之后,在您的web.xml中添加以下行:

<filter>
  <filter-name>cors</filter-name>
  <filter-class>MY.PACKAGE.SimpleCORSFilter</filter-class>
 </filter>

 <filter-mapping>
  <filter-name>cors</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
@H_403_1@那就是全部!

原文链接:https://www.f2er.com/ajax/160149.html

猜你在找的Ajax相关文章