Parcel 2 Dev Server路由配置:非存在路由返回404而非跳转入口
如何让Parcel 2开发服务器对不存在的路由返回404状态码?
我用Parcel 2搭建了开发服务器,配置了src/index-1.html和src/index-2.html两个入口文件,对应的http://0.0.0.0:3000/index-1.html和http://0.0.0.0:3000/index-2.html都能正常访问,但访问不存在的路由(比如http://0.0.0.0:3000/test)时,服务器会自动重定向到第一个入口文件index-1.html。我想配置成让这类不存在的路由直接返回404状态码,请问该怎么调整?
我的服务器启动代码如下:
const { Parcel } = require('@parcel/core') let bundler = new Parcel({ entries: [ 'src/index-1.html', 'src/index-2.html' ], mode: 'development', logLevel: 'warn', defaultTargetOptions: { publicUrl: '/', distDir: './dist', shouldScopeHoist: false, sourceMaps: true, includeNodeModules: true, shouldOptimize: false, engines: { browsers: ['ie >= 11'] } }, shouldAutoInstall: true, shouldDisableCache: false, shouldContentHash: true, serveOptions: { publicUrl: '/', host: '0.0.0.0', port: 3000, https: false }, hmrOptions: { port: 3000, host: '0.0.0.0' } }) bundler.watch((err, event) => { if (err) { // fatal error throw err } if (event.type === 'buildSuccess') { let bundles = event.bundleGraph.getBundles() console.log(`✨ Built ${bundles.length} bundles in ${event.buildTime}ms!`); } else if (event.type === 'buildFailure') { console.log(event.diagnostics) } })
解决方案
Parcel 2开发服务器默认启用了SPA fallback机制,当请求的资源不存在时会自动返回第一个入口文件,以此适配单页应用的路由需求。要让不存在的路由返回404,只需要在serveOptions中添加fallback: false即可禁用该机制:
const { Parcel } = require('@parcel/core') let bundler = new Parcel({ entries: [ 'src/index-1.html', 'src/index-2.html' ], mode: 'development', logLevel: 'warn', defaultTargetOptions: { publicUrl: '/', distDir: './dist', shouldScopeHoist: false, sourceMaps: true, includeNodeModules: true, shouldOptimize: false, engines: { browsers: ['ie >= 11'] } }, shouldAutoInstall: true, shouldDisableCache: false, shouldContentHash: true, serveOptions: { publicUrl: '/', host: '0.0.0.0', port: 3000, https: false, fallback: false // 禁用SPA fallback,返回404 }, hmrOptions: { port: 3000, host: '0.0.0.0' } }) bundler.watch((err, event) => { if (err) { throw err } if (event.type === 'buildSuccess') { let bundles = event.bundleGraph.getBundles() console.log(`✨ Built ${bundles.length} bundles in ${event.buildTime}ms!`); } else if (event.type === 'buildFailure') { console.log(event.diagnostics) } })
扩展:自定义404页面
如果需要返回自定义的404页面而非默认的空白404,可以将fallback设置为你的404页面路径,比如src/404.html:
serveOptions: { // ...其他配置 fallback: 'src/404.html' }
此时访问不存在的路由时,服务器会返回src/404.html的内容,同时状态码保持为404。
内容的提问来源于stack exchange,提问作者Asobitu
相关产品推荐
相关产品推荐

