jquery cors发帖请求不起作用

时间:2017-03-27 14:56:32

标签: jquery rest post cors

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

以下是帖子请求的代码:

lambda

服务器端代码在这里:

/**
 * 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)
        }
    });
};

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

  

阻止跨源请求:同源策略禁止读取   远程资源在   http://localhost:8080/aigateway/rest/ioconfiguration/1。 (原因:CORS   标题'Access-Control-Allow-Origin'缺失。)

在我看来,我的CORS过滤器无效。

但是如果我从RESTeasy发送帖子请求

  

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

它会给我200 OK回复,并提供正确的信息,如

  

{ “ioConfigurationId”: “CH1”, “活性”:真, “姓名”: “123”, “conversionType”: “线性”, “明复”:5.93, “bInfo”:0.32, “voltageDivide”: “/ 4”, “sampleRange”:“24   位 “ ”samplePeriod“:10 ”storeRaw“:假 ”storeConverted“:假 ”defaultGraph“: ”线“, ”标题“: ”“, ”单元“: ”“, ”rangeLowerbound“:0,” rangeUpperbound “:100,” 代码 “:” 功能   conversion_CH1(输入){\ n \ treturn input; \ n}“}

我可以检查标题,它是:

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

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

有关详细信息,请参阅以下设置CORS过滤器的方法:

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

的web.xml:

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

}

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

谢谢!

修改

根据NrN的说法,我已经删除了CORS过滤器中的 Access-Control-Allow-Credentials 字段,但它仍然无效。

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

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

这是Response标头: 响应标题:

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

1 个答案:

答案 0 :(得分:-1)

这里有两个问题。

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

  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