添加自定义请求标头

时间:2013-11-03 00:25:29

标签: jquery ajax api spring-mvc xmlhttprequest

我有一个API。我正在尝试使用Ajax Jquery向我的api发送请求但是有问题。以下是我的Ajax请求。我正在以JSON格式发送数据,而且我需要添加两个请求标头(signedInUserId& accessToken)。但这不起作用。

  $.ajax( {
                        type: "PUT",
                        contentType: 'application/json',
                        dataType: 'json',
                        beforeSend: function(xhr) { 
                            xhr.setRequestHeader("signedInUserId", "1");
                            xhr.setRequestHeader("accessToken", "testtoken");
                          },
                        url: "url to my api",
                        data: JSON.stringify(data), 
                        success: function( response ) { 
                                 // $('#successMessage').html(response);
                        },
                        complete: function() {
                            //message
           }
                    });         

虽然,如果我发送没有自定义标头的请求(signedInUserId& accessToken),并且在我的api控制器中我注释了自定义标头参数,它的工作绝对正常。下面是我的api控制器代码。

    @RequestMapping(value = "test.json", method = { PUT })
public @ResponseBody
Map<String, ? extends Object> test(HttpSession session, @RequestHeader Integer signedInUserId, @RequestHeader String accessToken, @RequestBody MyTestModel myTestModel) {

// working

}

我很困惑为什么在发送自定义标头时它无法正常工作,发送自定义标头时是否有问题?

编辑: 以下是我的请求和响应标题。

       Request URL:http URL....
       Request Method:OPTIONS
       Status Code:200 OK
       Request Headersview parsed
       OPTIONS /Url/url/add.json HTTP/1.1
       Host: local host:8080
       Connection: keep-alive
       Access-Control-Request-Method: PUT
       Origin:url
       User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36   (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
       Access-Control-Request-Headers: accept, accesstoken, signedinuserid, content-       type
       Accept: */*
       Referer: url
       Accept-Encoding: gzip,deflate,sdch
       Accept-Language: en-US,en;q=0.8
       Response Headersview parsed
       HTTP/1.1 200 OK
       Server: Apache-Coyote/1.1
       Access-Control-Allow-Origin: *
       Access-Control-Allow-Methods: GET, OPTIONS, POST, PUT, DELETE
       Access-Control-Allow-Headers: Content-Type, x-requested-with
       Access-Control-Max-Age: 1800
       Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
       Content-Length: 0
       Date: Sun, 03 Nov 2013 19:11:20 GMT

1 个答案:

答案 0 :(得分:1)

显然问题是由于服务器响应中允许的标头。在我的服务器设置中,响应中允许的标头如下:

response.addHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with"); 

因此,我在允许的标头中添加了两个标头accessToken和signedInUserId,响应标头现在如下所示:

response.addHeader("Access-Control-Allow-Headers", "Content-Type, accessToken, signedInUserId, x-requested-with"); 

我想这就是为什么请求不超出预检请求(OPTION)的问题,因为我发送的标头不允许在服务器发送的响应标头中。如果我错了,请纠正我。