我正在尝试将我的 React 应用程序部署到 Azure,并在子 URL /web/ 下提供服务。该应用程序在本地主机上完美运行,但在 Azure 上无法按预期运行。具体来说,favicon.ico 和 logo.jpg 等静态资源无法加载,并且路由似乎行为不当。 azure 没有出现 502 错误。
反应配置:
{ "homepage": "/web/" }
index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from "react-router-dom";
import { ConfigProvider } from './utils/ConfigContext';
const AppWithRouter = () => {
return (
<BrowserRouter basename="/web/">
<App />
</BrowserRouter>
);
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<ConfigProvider>
<AppWithRouter />
</ConfigProvider>
);
公共文件夹:
public/
├── favicon.ico
├── logo.jpg
├── index.html
nginx配置:
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
location /web/ {
try_files $uri /index.html;
}
location /web/static/ {
alias /usr/share/nginx/html/static/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
routes.json
{
"routes": [
{
"route": "/web/*",
"serve": "/index.html",
"statusCode": 200
}
]
}
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" href="/web/favicon.ico" />
<meta charset="utf-8" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
反应资产路径:
<Link to="/">
<img
src="web/logo.jpg"
alt="Company Logo"
className="logo"
/>
</Link>
我的配置中做错了什么导致应用程序在 Azure 上崩溃?
我尝试了带有路由的示例 Reactjs 应用程序,并将其部署到 Azure Web App。
通过使用下面的代码,我能够在部署到生产环境后成功加载 favicon.ico 和 logo.jpg。
index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './components/App';
import { BrowserRouter } from "react-router-dom";
import { ConfigProvider } from './utils/ConfigContext';
const BASENAME = '/web';
const AppWithRouter = () => {
return (
<BrowserRouter basename={BASENAME}>
<App />
</BrowserRouter>
);
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<ConfigProvider>
<AppWithRouter />
</ConfigProvider>
);
App.js:
import React from 'react';
import { Routes, Route, Link } from 'react-router-dom';
const Home = () => (
<div>
<h1>Home Page</h1>
<p>Welcome to the Home Page of our application!</p>
</div>
);
const About = () => (
<div>
<h1>About Page</h1>
<p>This is the About Page. Learn more about us here!</p>
</div>
);
const App = () => {
return (
<div>
<header>
{}
<Link to="/">
<img
src="web/logo.jpg"
alt="Company Logo"
className="logo"
/>
</Link>
<nav>
<ul className="nav-links">
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
</header>
<main>
{}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</main>
<footer>
<p>© 2025 Your Company. All rights reserved.</p>
</footer>
</div>
);
};
export default App;
Azure Web 应用程序输出: