【问题标题】:jquery cors post request not workingjquery cors发布请求不起作用
【发布时间】:2017-08-20 08:38:47
【问题描述】:

我在执行 CORS 发布请求时遇到问题。

这里是发布请求的代码:

/**
 * function to update channel information
 * @returns {undefined}
*/
this.postNameInfo = function() {
    var channel = self.selected.split("-")[0];
    var id = channel.replace("CH","");
    $.ajax({
        url: self.ioConfigurationUrl + "/" + id,
        type: "POST",
        data: {
            "data": "name:" + $("#name")[0].value
        },
        success: function() {
            console.log("Change name succeed!");
            self.updateIoInfo();
            self.updateStorageInfo();
            $("#title").val($("#name")[0].value);
            self.postTitleInfo();
        },
        error: function() {
            console.log("Failed to change name of " + channel)
        }
    });
};

服务器端代码在这里:

  @POST
  @Path("/{id : \\d+}")
  @Produces(MediaType.APPLICATION_JSON)
  public Response updateIOConfig(@PathParam("id") Integer id, @QueryParam("data") String data) {
    if (!ChannelName.isValidChannel(id)) {
      return Response.status(Response.Status.NOT_FOUND).build();
    }
    init();
    IOConfiguration ioConfig = ioConfigurationDAO.findIOConfiguration("CH" + id);
    String key = data.split(":")[0];
    String value = data.split(":")[1];
    if (!ioConfigurationDAO.getManager().getTransaction().isActive()) {
      ioConfigurationDAO.getManager().getTransaction().begin();
    }
    System.out.println(data);
    if (key.equals("name")) {
      ioConfigurationDAO.changeName(ioConfig.getIoConfigurationId(), value);
      ioConfigurationDAO.getManager().getTransaction().commit();
      if (ioConfig.getDataSeriesMeta() != null && ioConfig.getDataSeriesMeta().size() != 0) {
        List<DataSeriesMeta> list = ioConfig.getDataSeriesMeta();
        DataSeriesMetaDAO dataSeriesMetaDAO = new DataSeriesMetaDAO();
        dataSeriesMetaDAO.setManager(ioConfigurationDAO.getManager());
        if (!dataSeriesMetaDAO.getManager().getTransaction().isActive()) {
          dataSeriesMetaDAO.getManager().getTransaction().begin();
        }
        for (DataSeriesMeta d : list) {
          dataSeriesMetaDAO.changeName(d.getDataSeriesMetaId(), value);
        }
        dataSeriesMetaDAO.getManager().getTransaction().commit();
        return Response.status(Response.Status.OK).entity(ioConfig).build();
      }
    }...
}

在我的服务器端,我总是收到空值,浏览器会给我这个错误:

跨域请求被阻止:同源策略不允许读取 远程资源在 http://localhost:8080/aigateway/rest/ioconfiguration/1。 (原因:CORS 缺少标头“Access-Control-Allow-Origin”)。

在我看来,我的 CORS 过滤器不起作用。

但是如果我从 RESTeasy 发送 post 请求到

http://localhost:8080/aigateway/rest/ioconfiguration/1?data=name:123

它会给我一个带有正确信息的 200 OK 响应,例如

{"ioConfigurationId":"CH1","active":true,"name":"123","conversionType":"Linear","mInfo":5.93,"bInfo":0.32,"voltageDivide": "/4","sampleRange":"24 位","samplePeriod":10,"storeRaw":false,"storeConverted":false,"defaultGraph":"Line","title":"","unit":"","rangeLowerbound":0," rangeUpperbound":100,"code":"函数 Conversion_CH1(输入){\n\treturn 输入;\n}"}

我可以检查标题,它是:

X-Powered-By    Undertow/1
Access-Control-Allow-Headers    origin, content-type, accept, authorization, Access-Control-Request-Method, Access-Control-Request-Headers
Server  WildFly/10
Date    Mon, 27 Mar 2017 14:41:24 GMT
Connection  keep-alive
Access-Control-Allow-Origin     *
Access-Control-Allow-Credentials    true
Content-Type    application/json
Content-Length  357
Access-Control-Allow-Methods    GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Max-Age  1209600

这就是我在我的 CORS 过滤器中添加的内容,它在 RESTeasy 中有效,但在我的项目中却没有,这太奇怪了,我不知道为什么。

有关更多信息,以下是我设置 CORS 过滤器的方法:

@Provider
public class CORSFilter implements ContainerResponseFilter {

  @Override
  public void filter(final ContainerRequestContext requestContext,
      final ContainerResponseContext cres) throws IOException {
    cres.getHeaders().add("Access-Control-Allow-Origin", "*");
    cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
    cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    cres.getHeaders().add("Access-Control-Max-Age", "1209600");
    cres.getHeaders().add("Access-Control-Allow-Headers",
        "origin, content-type, accept, authorization, Access-Control-Request-Method, Access-Control-Request-Headers");
  }

}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>servlet 3.0 Web Application</display-name>
    <context-param>
        <param-name>resteasy.providers</param-name>
        <param-value>
                com.sensorhound.aigateway.ws.filters.CORSFilter
        </param-value>
    </context-param>
    <servlet>
        <servlet-name>ServletContainer</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.sensorhound.things.rest.ThingsApplication</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletContainer</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

如果您需要更多信息,我愿意分享。

谢谢!

编辑

根据 NrN,我已经删除了我的 CORS 过滤器中的 Access-Control-Allow-Credentials 字段,但它仍然不起作用。

这是我浏览器网络控制台中的请求标头: 请求标头: 接受*/*

Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Content-Length 18
Content-Typet ext/plain
Host localhost:8080
Origin null
User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0

这是响应标头: 响应标头:

Connection keep-alive
Content-Length 9437
Content-Type text/html;charset=UTF-8
Date Tue, 28 Mar 2017 21:16:46 GMT

【问题讨论】:

    标签: jquery rest post cors


    【解决方案1】:

    这里有两个问题。

    1. 在 Jquery 客户端请求中,您没有将 withCredentials 属性设置为 true,但服务器正尝试将 Access-Control-Allow-Credentials 响应为 true。将其放在 ajax 调用中。 xhr 字段:{ withCredentials: 真 }

    2. 当您将 Access-Control-Allow-Credentials 设置为“true”时,您不能将 Access-Control-Allow-Origin 设置为“*”。您必须指定特定来源而不是通配符。 更多细节在这里https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials

    【讨论】:

    • 嗨,NrN,感谢您的评论。我已删除过滤器中的“Access-Control-Allow-Credentials”字段。但它仍然没有工作。我在 EDIT 中提供了有关我的请求标头和响应标头的更多信息,如果您有时间,请查看。谢谢!
    猜你喜欢
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    相关资源
    最近更新 更多