首页 > 解决方案 > 当我使用来自前端的 ajax 请求访问 Tomcat、maven 中的 db 时出现 CORS 标头错误

问题描述

所以我创建了这个资源,它返回一个产品数组。

public class MyResource {

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Object getbook()
    {
        Products p = new Products();
        
        
        Gson gson = new GsonBuilder().create();
        return gson.toJson(p.getAll());
    }

但是当我从我的前端调用这个 api 时,它说从源 'http://localhost:8083' 访问 XMLHttpRequest 在 'http://localhost:8085/demoRest/webapi/myresource' 已被 CORS 策略阻止:否请求的资源上存在“Access-Control-Allow-Origin”标头。

这是我的ajax请求

$(function() {
var val = "";
$("#submit").click(function(event){
    event.preventDefault();

    $.ajax({
        type: "GET",
        dataType:"json",
        url:  "http://localhost:8085/demoRest/webapi/myresource",
        success: function(data) {
            console.log("response:" + data);
            //$.each(data, function(j, pdata) {
              //  val= val + "[ "+pdata.title +" " + pdata.author +"]";
           // });
           // $("#data").text(val);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(' Error in processing! '+textStatus);
        }
    });
});
});

我的 Webxml

<servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.demoRest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>

使用 tomcat 版本 10

标签: javamaventomcat

解决方案


所以我想你应该了解 CORS 政策。

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

如果您在未经主机 B 许可的情况下从主机 A 向主机 B 使用 XMLHttpRequest,用户将阻止该请求。

但是,我们可以通过在主机 B 上添加一些标头来绕过 CORS。后端 api 经常使用此策略来处理来自不同主机的许多不同请求。

你可以在这里举个例子:

((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Origin", "*");
((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");

更多详情:

https://howtodoinjava.com/java/servlets/java-cors-filter-example/


推荐阅读