我有一个 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