post sets headers

d911deng000 注册会员
2023-02-25 10:14

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > in the POST request, you can set the request header(headers) pass additional information to server, Such as authentication information, content types, and so on.

In JavaScript, you can use the XMLHttpRequest object or the fetch function to send the POST request and set the request header. Here is sample code that uses the fetch function to send a POST request and set the request header:

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json', // 设置内容类型为 JSON
    'Authorization': 'Bearer ' + token, // 设置认证信息
    // 其他自定义请求头
  body: JSON.stringify(data) // 设置请求体(body)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

In the example code above, the headers option is an object whose attribute name represents the key of the request header and whose attribute value represents the value of the request header. You need to set the request headers as specified in the interface documentation. For example, in the above example code, the Content-Type request header is set to application/json, indicating that the format of the request body is JSON. Authorization request headers are set up Bearer + tokens to indicate using OAuth 2.0 authentication mechanism and passing access tokens.

Note that if your request header contains special characters(e.g., colons, Spaces, etc.), you need to URL code. The value of the request header can be encoded using the encodeURIComponent function. For example:

headers: {
  'Content-Type': 'application/x-www-form-urlencoded',
  'Authorization': 'Basic ' + btoa(clientId + ':' + clientSecret),
  'Custom-Header': encodeURIComponent('header value with spaces and :'),

About the Author

Question Info

Publish Time
2023-02-25 10:14
Update Time
2023-02-25 10:14