在Angular 9中获取响应头变量

问题描述 投票:0回答:1

我想通过后台获取一个我在头部声明的变量,但是这个代码不能用。

在我的后台:(express + knex):

    async login(req, res) {
    const {
      user_name,
      email
    } = req.body;

    let {
      id
    } = await connetion('user')
      .where('email', email)
      .andWhere('user_name', user_name)
      .select(['id'])
      .first();

    if (id == undefined) {
      console.log('entrou no if'.italics.blue);

      await connetion('user').insert({
        user_name,
        email
      })

      let {
        id
      } = await connetion('user')
        .where('email', email)
        .andWhere('user_name', user_name)
        .select(['id'])
        .first();

      res.header('authorization', id);
      console.log(id);


      console.log('\n<ยบ>'.bold.yellow + ' novo usuario '.cyan + user_name + ' criado e logado'.cyan);
      res.status(201).send(); //? 201 : created
      return res.json({
        id
      })
    }

我是我的service.ts(angular):

    import { retry, map } from 'rxjs/operators';
    import { host } from './host';
    import { User } from './../models/user';
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';

    @Injectable({providedIn: 'root'})
    export class AuthService {
      constructor(private http: HttpClient) {}

      public login(user: User): any {
        return this.http.post(host+'/login', user, {observe: 'response', headers: 'autorization'})
          .pipe(
            map(res => { return res})
          ) 
      }
    }

我是我的component.ts(angular):

  login(){
    this.authService.login(new User({
        user_name: this.user_name,
        email: this.email
      })
    ).pipe(first())
    .subscribe(
      ((data: HttpResponse<any>) => {
        console.log("response :");
        console.log(data);
        console.log("response.headers: ");
        console.log(data.headers);
        console.log("response.headers.get('authorization'): ");
        console.log(data.headers.get('authorization'));
      })
    )

console.logs:1

这里是在响应头(网络表)的授权。

2

拜托,如果你能帮我解决这个问题,我会给你一个大大的虚拟拥抱(隔离)

angular http-headers httpclient angular-httpclient angular-http
1个回答
0
投票

在你的后端响应头中,你必须添加以下内容

Access-Control-Expose-Headers:授权。

© www.soinside.com 2019 - 2024. All rights reserved.