【问题标题】:Is it possible to open a webpage with headers?是否可以打开带有标题的网页?
【发布时间】:2021-06-29 16:23:05
【问题描述】:
是否可以打开带有标题的网页?
我需要能够在标头中传递 JWT,而不是查询参数。
查询参数可以保存到日志中,存在安全隐患。
我知道使用 window.open() 打开带有标题的网页是不可能的,但是使用 Vanilla Javascript 可以吗?
如果是,那怎么办?
我正在使用 React 来构建这个概念证明。
【问题讨论】:
标签:
javascript
reactjs
header
authorization
window.open
【解决方案1】:
无法使用window.open() 发送标头,也无法打开带有标头的新页面,但可以在一页内使用 javascript:
获取示例:
fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
}
XMLHttpRequest 示例:
var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Request finished. Do processing here.
}
}
xhr.send("foo=bar&lorem=ipsum");