Express 如何将响应头添加到NextJS公共资产?
我想在NextJS中为我的图像和字体设置Express 如何将响应头添加到NextJS公共资产?,express,http-headers,next.js,response-headers,Express,Http Headers,Next.js,Response Headers,我想在NextJS中为我的图像和字体设置max age响应标题 我从NextJS中找到了这个文档,但由于我使用的是next compose插件,因此如何将它合并到我当前的代码中并不十分明确 我已经设置了一个express服务器,所以如果有必要,可以利用它,但同样不确定在哪里以及如何在那里设置头 我当前的next.config.js(NextJS v9.5.5): Server.js: const express = require( 'express' ); const next = r
max age
响应标题
我从NextJS中找到了这个文档,但由于我使用的是next compose插件
,因此如何将它合并到我当前的代码中并不十分明确
我已经设置了一个express服务器,所以如果有必要,可以利用它,但同样不确定在哪里以及如何在那里设置头
我当前的next.config.js(NextJS v9.5.5):
Server.js:
const express = require( 'express' );
const next = require( 'next' );
const bodyParser = require('body-parser');
const compression = require('compression');
// Import middleware.
const pageRoutes = require( './routes/pageRoutes' );
// Setup app.
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler();
const handler = pageRoutes.getRequestHandler( app );
// setup server
app.prepare()
.then( () => {
// Create server.
const server = express();
// this is for forms
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());
server.use(compression());
const formRoutes = require( './routes' );
formRoutes(server);
// Use our handler for requests.
server.use( handler );
// Don't remove. Important for the server to work. Default route.
server.get( '*', ( req, res ) => {
res.setHeader("test", 25);
return handle( req, res );
} );
// Get current port.
const port = process.env.PORT || 8080;
// Error check.
server.listen( port, err => {
if ( err ) {
throw err;
}
// Where we starting, yo!
console.log( `> Ready on port ${port}...` );
} );
} );
在nextConfig的声明中,只是一个地方
async headers() {...},
因此,最终它将成为
const nextConfig = {
async headers() {
return [
{
source: '/:all*(svg|jpg|png)',
locale: false,
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=9999999999, must-revalidate',
}
],
},
],
},
serverRuntimeConfig: { // Will only be available on the server side
},
publicRuntimeConfig: { // Will be available on both server and client
DOMAIN: process.env.NODE_ENV == 'production' ? 'http://example.com' : 'https://example.local',
SITENAME: process.env.NODE_ENV == 'production' ? 'Site Name' : 'Local Site Name'
}
}
谢谢,我试试看。
const nextConfig = {
async headers() {
return [
{
source: '/:all*(svg|jpg|png)',
locale: false,
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=9999999999, must-revalidate',
}
],
},
],
},
serverRuntimeConfig: { // Will only be available on the server side
},
publicRuntimeConfig: { // Will be available on both server and client
DOMAIN: process.env.NODE_ENV == 'production' ? 'http://example.com' : 'https://example.local',
SITENAME: process.env.NODE_ENV == 'production' ? 'Site Name' : 'Local Site Name'
}
}