【问题标题】:How to get entire http response using Angular 8如何使用 Angular 8 获取整个 http 响应
【发布时间】:2019-10-10 18:18:03
【问题描述】:

我正在使用 Angular 8,我想将 session-idcsrf-token 设置为 cookie。 所以我需要从http响应中得到这两个。但是当我使用 HttpClient 发送请求时,我只是在 subscribe 方法中收到响应的正文。 那么我需要做什么呢?

Authentication.service.ts:

export class AuthenticationService {
  private BASE_URL = 'http://192.168.1.12:8000/';

  constructor(private http: HttpClient) {
  }

  signIn(user) {
    return this.http.post(this.BASE_URL + 'api/auth/', user)
      .subscribe((resp: Response) => {
        console.log(resp.headers);
      });
  }
}

Authentication.component.ts:

export class AuthenticationComponent implements OnInit {
  private body;

  constructor(private authService: AuthenticationService) {
  }

  ngOnInit() {
    this.body = {
      username: 'foo',
      password: 'foo'
    };
  }

  logIn() {
    this.authService.signIn(this.body);
  }

更新:

这是我来自服务器的回复:

response screen shot

以及我从控制台日志中获取的内容:

console log screenshot

【问题讨论】:

  • 你能展示一下你的resp是什么样的吗??
  • 它会自动设置在cookies下,一从服务器返回,你检查过cookies下吗?
  • 是的,它作为 cookie 返回,但未设置为浏览器 cookie。我想访问标头以将它们设置为 cookie

标签: angular angular8


【解决方案1】:

您必须检查服务器(后端)是否在属性中包含这两个标头 - Response.headers,用于您正在执行的 POST 请求。您也可以从前端代码执行此检查。像这样更改您的 signIn 方法:

  signIn(user) {
    return this.http.post(this.BASE_URL + 'api/auth/', user)
      .subscribe((resp: Response) => {
        console.log(resp.headers);
      });
  }

如果这两个属性(session-id 和 csrf-token)存在于 headers 对象中,请检查控制台语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-07
    • 2020-08-14
    • 2019-10-07
    • 2017-02-21
    • 2020-05-15
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    相关资源
    最近更新 更多