问题描述
我想从HTTP响应标头中获取信息。我使用以下代码示例执行HTTP请求。
var token = '123456';
var r = new XMLHttpRequest();
r.open('get','/api/users/@me');
r.setRequestHeader('authorization',token);
r.send();
在下一步中,服务器检查请求标头是否包含有效的授权令牌。如果令牌有效,则服务器发送响应。
app.get('/api/users/@me',(req,res) => {
if (req.headers.authorization == '123456') {
console.log(true);
res.send('valid token!');
}
});
现在,我计划获取请求并在页面上显示请求的内容(“有效令牌!”),但是我不知道如何执行此操作。
我还尝试过这样的请求:
fetch('https://localhost/api/users/@me',{
headers: {
authorization: '123456'
}
}).then(result => {
//...
})
解决方法
res.send('valid token!')
导致“有效令牌”文本包含在响应正文中。在客户端,使用result.text()
方法读取响应正文的文本内容。如果这是一个json响应,那么您将使用result.json()
。
fetch('https://localhost/api/users/@me',{
headers: {
authorization: '123456'
}
}).then(result => {
console.log(result.text())
})
其他类似于.text()的方法在这里列出: https://developer.mozilla.org/en-US/docs/Web/API/Response