我正在尝试构建一个前端界面来与 API 服务进行通信,我使用 HTML、CSS 和 JavaScript。我正在使用 async 函数/await fetch 调用 API 和 response.jsom 从响应中检索 JSON 数据,现在我必须将 X-Authorization:Bearer Token '.....' 添加到标头,我该如何用 JavaScript 做到这一点?
在标头中添加您的令牌,这是一个示例,在应用程序的任何位置调用此 postData 函数,您可以将其添加到公共位置
另请检查 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch 这是详细的解释
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
let token = "Get your token here, Store it in local storage and read it from local storage is a better method"
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
"X-Authorization":Bearer Token '.....' // Here you can add your token
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});