我有一个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
显然,问题出在服务器响应中允许的标头。在我的服务器设置中,作为响应,允许的标头如下:
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)的问题,因为服务器发送的响应头中不允许我正在发送的头。如果我错了,请纠正我。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句