我正在使用哈希路由来处理 React JS 应用程序。在本地环境中应用程序运行良好。
例如https://stackoverflow.com/posts/ 应该是应用程序的 URL,但它不起作用,我必须使用 https://stackoverflow.com/posts/index.html 才能使其工作。
部署后,我发现它正在下载名为“download”的空文件,而不是提供构建文件中预设的index.html文件。为了在服务器上运行构建,我使用 S3 和 CloudFront 架构。
现在,我无法确定 HASH 路由是否行为错误或者 AWS 部署出现问题。
使用 React JS 的代码片段
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './redux/store';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { HashRouter } from 'react-router-dom/cjs/react-router-dom';
ReactDOM.render(
<Provider store={store}>
<HashRouter>
<App />
</HashRouter>
</Provider>
document.getElementById('root')
);
部分package.json内容
{
"name": "loremipsum",
"version": "0.1.0",
"private": true,
"homepage": "/loremipsum/"
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
是否需要部署在子目录上?如果是,您将必须更改
package.json文件的内容,以强制相对于index.html文件提供资源。{ "name": "loremipsum", "version": "0.1.0", "private": true, "homepage": ".", "scripts": { "build": "react-scripts build", "build-prd": "PUBLIC_URL=http://www.foo/relativepath react-scripts build" // ... } }有了这个,我们将能够将托管在
http://www.foo中的应用程序移动到http://www.foo/relativepath甚至https://www.foo/bar1/bar2/无需重建。您还必须覆盖
PUBLIC_URL以包含您想要托管文件的域和子目录