No Access-Control-Allow-Origin header is present on the requested resource

前端 未结 4 1291
感情败类
感情败类 2020-12-05 05:08

I want to access information from same domain but with different port number, To allow this I am adding Access-Control-Allow-Origin with the response header.

相关标签:
4条回答
  • 2020-12-05 05:51

    Solution:
    Instead of using setHeader method I have used addHeader.

    response.addHeader("Access-Control-Allow-Origin", "*");
    

    * in above line will allow access to all domains, For allowing access to specific domain only:

    response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
    

    For issues related to IE<=9, Please see here.

    0 讨论(0)
  • 2020-12-05 05:52

    I find the solution in spring.io,like this:

        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");
    
    0 讨论(0)
  • 2020-12-05 05:59

    You are missing 'json' dataType in the $.post() method:

    $.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'})
            .done(function(data){
                      alert(data);
             }, "json");
             //-^^^^^^-------here
    

    Updates:

    try with this:

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    

    0 讨论(0)
  • 2020-12-05 06:07

    On your servlet simply override the service method of your servlet so that you can add headers for all your http methods (POST, GET, DELETE, PUT, etc...).

    @Override
        protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    
            if(("http://www.example.com").equals(req.getHeader("origin"))){
                res.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
                res.setHeader("Access-Control-Allow-Headers", "Authorization");
            }
    
            super.service(req, res);
        }
    
    0 讨论(0)
提交回复
热议问题