如何从 getServerSideProps 访问 NextJS 响应正文?

时间:2021-07-26 17:43:34

标签: node.js next.js

我需要在 HTML 文档上设置自定义响应标头,该标头的值来自响应正文。我发现可以使用 getServerSideProps 来完成,但是到目前为止,找到一种方法来访问该函数中的响应主体是很困难的。当控制台记录 context.res 对象内的所有键时,我正在寻找的一个可能突出的字段是 outputData,尽管记录时的值始终是一个空数组。

getServerSideProps 上的 NextJS docs 表示 res 键是 HTTP response object。布尔值 finished 字段及其较新的 writableEnded 对应项总是返回值为 false。所以我想知道是否可以在 getServerSideProps 中做任何事情让我添加

ctx.res.setHeader('x-custom-company-header', getHeader(responseBody));

其中 responseBody 是表示请求页面的 HTML 文档的字符串化响应。或者我是否必须使用其他一些 NextJS 可选功能/中间件才能实现这一点?

我在寻找解决方案时发现了 this discussion。但这似乎只与 POST 请求相关,因为添加

const body = await parseBody(context.req, '1mb');
console.log('body here:');
console.dir(body);

仅在终端中为该值生成一个空字符串。

1 个答案:

答案 0 :(得分:1)

如果您绝对必须在 getServerSideProps 中执行此操作,您可以覆盖 res.end 并捕获 Next.js 传递给它的生成的 HTML。

export async function getServerSideProps({ res }) {
    const resEnd = res.end.bind(res) // Save current `res.end` into a variable to be called later
    res.end = html => {
        res.setHeader('x-custom-company-header', getHeader(html))
        resEnd(html)
        return
    }

    // Remaining code...
}