Java 请求的资源上不存在 Access-Control-Allow-Origin 标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20881532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:59:28  来源:igfitidea点击:

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

javascriptjavajqueryajaxcors

提问by Bhushan

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

我想访问来自同一域但具有不同端口号的信息,为此我添加Access-Control-Allow-Origin了响应标头。

Servlet Code:(present on www.example.com:PORT_NUMBER)

Servlet 代码:(出现在 www.example.com:PORT_NUMBER)

String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");//cross domain request/CORS
response.getWriter().write(json);

jQuery code:(present on www.example.com)

jQuery 代码:(出现在 www.example.com 上)

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

Several times I am getting this error(in console):

我多次收到此错误(在控制台中):

XMLHttpRequest cannot load 'http://www.example.com:PORT_NUMBER/MYSERVLET'
No 'Access-Control-Allow-Origin' header is present on the requested resource.

This error mostly occures first time when $.postgets executed. Second time it allows.

此错误主要发生在第一次$.post执行时。第二次它允许。

My question is that is there missing in servletor in jQuerycode?

我的问题是代码中servletjQuery代码中是否缺少?

Any suggestion will be appreciated.

任何建议将不胜感激。

Update1

更新1

I have changed:

我变了:

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

To:

到:

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

Then I am getting this error in console:

然后我在控制台中收到此错误:

XMLHttpRequest cannot load http://www.example.com:PORT_NUMBER/MyServletName
The 'Access-Control-Allow-Origin' whitelists only 'http://www.example.com'
Origin 'http://www.example.com' is not in the list,
and is therefore not allowed access.

[Note: whitelist and origin are same, but still it gives error. It works sometimes, and gives above error sometimes.]

[注意:白名单和来源相同,但仍然出错。它有时有效,有时会出现上述错误。]

Let me know if you need anymore information.

如果您需要更多信息,请告诉我。

采纳答案by Bhushan

Solution:
Instead of using setHeadermethod I have used addHeader.

解决方案
而不是使用setHeader我使用过的方法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.

有关 IE<=9 的问题,请参阅此处

回答by Jai

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

您在$.post()方法中缺少“json”数据类型:

$.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"));


回答by Richard Xue

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

我在spring.io 中找到了解决方案,如下所示:

    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");

回答by Alejandro Villarreal

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

在您的 servlet 上,只需覆盖 servlet 的服务方法,以便您可以为所有 http 方法(POST、GET、DELETE、PUT 等)添加标头。

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