如何获取响应的内容header?
How to get the content of a response header?
我想从 HTTP 响应中获取信息 header。我使用下面的代码示例执行 HTTP 请求。
var token = '123456';
var r = new XMLHttpRequest();
r.open('get', '/api/users/@me');
r.setRequestHeader('authorization', token);
r.send();
下一步,服务器会检查请求 header 是否包含有效的授权令牌。如果令牌有效,服务器将发送响应。
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
我想从 HTTP 响应中获取信息 header。我使用下面的代码示例执行 HTTP 请求。
var token = '123456';
var r = new XMLHttpRequest();
r.open('get', '/api/users/@me');
r.setRequestHeader('authorization', token);
r.send();
下一步,服务器会检查请求 header 是否包含有效的授权令牌。如果令牌有效,服务器将发送响应。
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