繁体   English   中英

在 angular 中获取 get 请求的响应标头

[英]Getting response headers for a get request in angular

我正在尝试使用基本身份验证进行获取请求,并且需要从响应标头中获取令牌。 我已经经历了类似的问题,并且正在按照那里的建议进行操作,但是我仍然无法获得所需的 header。 在此先感谢您的帮助。

这是我的代码:

testLogin(): Observable < any > {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': 'Basic ' + btoa('username:password')
    }),
    observe: 'response'
    as 'body'
  };
  return this.http.get < any[] > ('/login', httpOptions);
}

...

this.service.testLogin().subscribe(r => {
  console.log(r.headers);
});

控制台上打印以下内容:

HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit: () => {…}
lazyUpdate: null
normalizedNames: Map(0)
[[Entries]]
No properties
size: (...)
__proto__: Map
__proto__:
append: ƒ append(name, value)
applyUpdate: applyUpdate(update) { const key = update.name.toLowerCase(); switch (update.op) { case 'a': case 's': let value = update.value; if (typeof value === 'string') { value = [value]; } if (value.length === 0) { return; } this.maybeSetNormalizedName(update.name, key); const base = (update.op === 'a' ? this.headers.get(key) : undefined) || []; base.push(...value); this.headers.set(key, base); break; case 'd': const toDelete = update.value; if (!toDelete) { this.headers.delete(key); this.normalizedNames.delete(key); } else { let existing = this.headers.get(key); if (!existing) { return; } existing = existing.filter(value => {…}
clone: ƒ clone(update)
constructor: class HttpHeaders
copyFrom: copyFrom(other) { other.init(); Array.from(other.headers.keys()).forEach(key => {…}
delete: ƒ delete(name, value)
forEach: forEach(fn) { this.init(); Array.from(this.normalizedNames.keys()) .forEach(key => {…}
get: ƒ get(name)
getAll: ƒ getAll(name)
has: ƒ has(name)
init: init() { if (!!this.lazyInit) { if (this.lazyInit instanceof HttpHeaders) { this.copyFrom(this.lazyInit); } else { this.lazyInit(); } this.lazyInit = null; if (!!this.lazyUpdate) { this.lazyUpdate.forEach(update => {…}
keys: ƒ keys()
maybeSetNormalizedName: ƒ maybeSetNormalizedName(name, lcName)
set: ƒ set(name, value)
__proto__: Object

您是否从服务器端公开了令牌? 在您的控制台日志中,我没有看到任何令牌。 如果有令牌,那么您可以像r.headers.get('token_name')一样访问它。 如果您不从服务器端公开它,请查看此问题。 我可能认为前两个解决方案可以帮助你。

您必须设置observe响应:

const httpOptions = {
  headers: new HttpHeaders({
    "Content-Type": "application/json",
    Authorization: "Basic " + btoa("username:password")
  }),
  observe: "response"
};

另外,我认为您无法阅读所有响应标头。

您可以使用response.headers.keys()方法检查您可以阅读的内容。

this.service.testLogin().subscribe(response => {
  response.headers
    .keys()
    .forEach(keyName =>
      console.log(
        `The value of the ${keyName} header is: ${response.headers.get(
              keyName
            )}`
      )
    );
});

这是StackBlitz 上的工作示例代码,供您参考。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM