如何在不使用自定义服务器的情况下在 Next.js 中设置自定义 HTTP 响应标头? [英] How to set custom HTTP response headers in Next.js without using a custom server?

查看:38
本文介绍了如何在不使用自定义服务器的情况下在 Next.js 中设置自定义 HTTP 响应标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Next.js 应用程序,我想向 所有 页面添加一个自定义 HTTP 响应标头(我不需要它是可配置的 per 页).

I am working on a Next.js application, and I would like to add a custom HTTP response header to all pages (I don't need it to be configurable per page).

现在我想知道如何做到这一点, 不必设置自定义服务器.这甚至可能吗?如果有,怎么做?

Now I was wondering how to do that, without having to set up a custom server. Is this even possible? If so, how?

推荐答案

如果没有权衡,这可能是不可能的.Next.js 具有自动静态优化功能,因此可以静态导出的页面将导出为纯 .html 文件.并且 .html 文件不需要在服务器上执行代码,因此没有地方添加自定义 HTTP 标头.

It's probably not possible without tradeoffs. Next.js has Automatic Static Optimization, so pages that can be statically exported will be exported to plain .html files. And .html files require no code execution on a server so there is no place to add a custom HTTP header.

或者,您可以使用 _app.js 中的 getServerSideProps 在每个响应上添加自定义 HTTP 标头:

Alternatively, you could add custom HTTP headers on every response with getServerSideProps in _app.js:

export async function getServerSideProps(context) {

  // set HTTP header
  context.res.setHeader('Content-Type', 'application/json')

  return {
    props: {}, // will be passed to the page component as props
  }
}

拥有 getServerSideProps 会禁用静态优化,因为所有页面都只会在服务器端呈现.

But having getServerSideProps would disable static optimization as all pages will be only server-side rendered.

服务器端渲染

这篇关于如何在不使用自定义服务器的情况下在 Next.js 中设置自定义 HTTP 响应标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆