简体   繁体   English

在 Angular 中捕获 http 标头

[英]Capturing http headers in Angular

I would like to capture a token that I set in the http header inside my Angular application.我想捕获我在 Angular 应用程序内的 http 标头中设置的令牌。

This is how I am serving my Angular application :这就是我为我的 Angular 应用程序提供服务的方式:

var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var router = express.Router();
var utils = require('./utils);

console.log('——————————- Run on port '+ port);

/****************************** Router ***************************/
router.get('*', function(req, res){
    token = utils.generateToken(); 
    res.set('X-Auth', token).sendFile('index.html', { root: __dirname + '/public/app' });
});

This token that I am setting in the header is what I would like to capture inside my Angular application.我在标头中设置的这个令牌是我想在我的 Angular 应用程序中捕获的。 I am kind of lost on where and how to do that ?我有点迷失在哪里以及如何做到这一点? I am using Angular 9. Any hints where to start ?我正在使用 Angular 9。任何提示从哪里开始?

the http clent return JSON data if you want to read all respond body you need to set observe option to response now the result will be of type HttpResponse you can now read all respond header ,type, status http客户端返回JSON数据,如果你想读取所有响应主体,你需要设置观察选项来response现在结果将是HttpResponse类型,你现在可以读取所有响应头,类型,状态

http
  .get<any>('url', {observe: 'response'})
  .subscribe((res : HttpResponse) => {
    console.log(rep.headers.get('X-Token'));
    localStorage.setItem('token',res.headers.get('X-Token'))
  });

check this 👉 http reading the full response检查这个 👉 http 阅读完整的回复

You can get the headers from the Response Class like below:您可以从响应类中获取标题,如下所示:

http.get('/controller/action')
    .subscribe((response:Response) => {
       console.log(response.headers);
     });

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

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