Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
790 views
in Technique[技术] by (71.8m points)

ajax - 'Access-Control-Allow-Origin' error in Spring MVC + Zepto POST

I'm trying to POST a JSON object to my Spring MVC controller, but I only receive an Access-Control-Allow-Origin error.

My controller:

@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);
    }
}

My Zepto POST:

this.addUser = function (valeur, callback) {
    $.ajax({
        type: 'POST',
        url: 'http://127.0.0.1:8080/AgenceVoyage/user/add',
        data: JSON.stringify({"mail" : "[email protected]" , "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");
        }
    });
};

I tried with no stringify in POST request, with no headers in @RequestMapping.

My result:

OPTIONS http://127.0.0.1:8080/AgenceVoyage/user/add No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. zepto.min.js:2 XMLHttpRequest cannot load

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found the solution :

Firstly, create a new filter, which will set the header response :

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

}

After that, in your web.xml add those lines :

 <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>

and that all !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...