默认情况下,当存在空文件夹时,express.static 会触发301
重定向,添加正斜杠。
这就是我为自定义快速服务器禁用此重定向的方式。
server.use(
express.static(path.join(__dirname, "build"), {
redirect: false,
})
)
在开发模式下使用创建-反应-应用程序时是否可以配置redirect: false
npm start
?
看看下面的标题,我想 Express 是create-react-app
在开发模式下用来为 SPA 提供服务的。
加载 http://localhost:3001/privacy-guides 时的请求标头
HTTP/1.1 301 Moved Permanently
X-Powered-By: Express
Content-Type: text/html; charset=UTF-8
Content-Length: 195
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Location: /privacy-guides/
Vary: Accept-Encoding
简短的回答,没有。
正如@goto1指出的那样,以下内容不是好的做法,但帮助我了解了CRA中的事情是如何运作的。
当使用npm start
在开发模式下运行CRA时,webpack-dev-server用于为应用程序提供服务。 Webpack DevServer使用Express来提供文件,这解释了为什么浏览到文件夹会触发301
重定向(请参阅express.staticoptions.redirect
,默认值为true
(。
当路径名是目录时,重定向到尾随"/"。
我确认添加以下内容以禁用重定向node_modules/react-scripts/config/webpackDevServer.config.js
。
staticOptions: {
redirect: false
}
手动编辑此文件有点麻烦,但有效。不幸的是,我能找到的唯一合法的配置staticOptions
方法需要弹出。
create-react-app
是一个构建工具,而不是一个服务器。它的输出是一组静态html
/js
/css
文件,您可以自由地以任何您想要的方式提供服务。(npm run build
(
唯一以某种方式与create-react-app
一起使用的是开发服务器,它只能在开发人员计算机上使用,而不是在生产中使用。(npm start
(
如果您仍然需要覆盖create-react-app
配置,请查看专用工具,例如:
- https://github.com/timarney/react-app-rewired
- https://github.com/harrysolovay/rescripts
- https://github.com/gsoft-inc/craco