javascript - 使用 apollo-datasource-rest 从响应中读取 header

标签 javascript rest apollo

import { RESTDataSource } from 'apollo-datasource-rest';

export class Foo extends RESTDataSource {

    async getFoo(id) {
        const responseFoo = await this.get(`/api/v1/foo/${id}`);
        return FooReducer(responseFoo);
    }
}

假设我使用 this.get 执行 GET 请求。如何阅读响应中的 header ?这在 apollo-datasource-rest 包中是否完全缺失?

最佳答案

在RESTDataSource中的didRecieveResponse方法中,可以访问response对象。在 RESTDataSource 类中定义/覆盖如下:

export class Foo extends RESTDataSource {

    async didReceiveResponse(response, request) {
        // use this.authHeader value in the class anywhere
        this.authHeader = response.headers.get('authorization');
    }
    
    async getFoo(id) {
        const responseFoo = await this.get(`/api/v1/foo/${id}`);
        console.log(this.authHeader)
        return FooReducer(responseFoo);
    }
}

willSendRequest 方法(您可以在其中访问请求对象和设置 header 等)在触发 http 请求之前运行,并在收到来自 http 请求的响应后调用 didReceiveResponse 方法。

关于javascript - 使用 apollo-datasource-rest 从响应中读取 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60764956/

相关文章:

javascript - 不设置密码,环回无法更新扩展模型

javascript - Firebase Cloud 函数计算 child 大小

javascript - 如何显示评分星级 Laravel 和 Ajax

java - REST 服务是否应该包含非 Servlet 内容?

java - 从 RESTful Web 服务发送 JSON 时是否需要 DTO?

Azure Cosmos db 和函数 javascript sdk - 如何异步读取文档?

express - Apollo Server Express : Request entity too large

javascript - 如何获取选项的值(基于 API 数据)并将其传递到同一页面

c# - 一个 Web API Controller 中具有不同参数的两种 HTTP Post 方法

api - Apollo 服务器多个第三方 API