jquery ajax怎么通过header传递参数

帮我教下,jquery ajax怎么通过header传递参数
最新回答
┌胖胖糖〃

2024-05-06 02:48:35

首先的首先,涉及业务逻辑的输入是需要通过参数传递的,主要有三种方法:path, query, POST/PUT body

path: GET /api/user/123 其中的123通过path传递
query: GET /api/search_user?userId=123
body: POST /api/user-signup {username: 'john'}

不建议通过header传参的原因:
1. proxy 和 reverse proxy会drop header
2. 不利于传输object
3. HTTP access control (CORS) API 一般会设置Access-Control-Allow-Headers,分分钟教你做人。
4. 不利于dev和debug
5. Header长度限制

然后,如果你需要传header,比如Authorization,如下。

jQuery.ajax()

headers (default: {})
Type: PlainObject
An
object of additional header key/value pairs to send along with requests
using the XMLHttpRequest transport. The header X-Requested-With:
XMLHttpRequest is always added, but its default XMLHttpRequest value can
be changed here. Values in the headers setting can also be overwritten
from within the beforeSend function. (version added: 1.5)$.ajax({
url: '/path/to/service',
method: 'GET | POST | PUT | DELETE',
headers: {
'Authorization': 'Bearer <jwt token>',
'some-other-header': 'some value'
}
})
.done(function(data){...})
.fail(function(jqXHR){...})
.always(function(){...})