|project-name
| client
| public
| index.html
| server.js
↑ 项目结构
我的目的是在server.js中显示index.html(公开)。
[ 服务器.js ]
const express = require('express')
const app = express()
const path = require('path')
app.listen(8080, function() {
console.log('listening on 8080')
})
app.use(express.static(path.join(__dirname, 'client/public')))
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'client/public/index.html'))
})
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/public/index.html'))
})
我按照上面的方式编写了代码,但是当我运行node server.js打开服务器并连接到localhost:8080时,没有任何反应。
看起来路径没有错,但是我奇怪为什么我做的React项目出不来。
[ 公共 > index.html ]
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/public/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="/public/logo192.png" />
<link rel="/manifest" href="/public/manifest.json" />
<title>Project Name</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
[客户端中的index.js]
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom'; // 추가됨
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
reportWebVitals();
[ 客户端中的 App.js ]
import React from 'react'
import { Route, Routes } from 'react-router-dom'
import Main from './pages/Main'
import Login from './pages/Login'
import Register from './pages/Register'
function App() {
return (
<div className='App'>
<div>
<Routes>
<Route path='/' element={<Main />} />
<Route path='/login' element={<Login />} />
<Route path='/register' element={<Register />} />
</Routes>
</div>
</div>
);
};
export default App;
如果您需要更多代码,请告诉我。
这是渲染公共 HTML 文件的最佳方式。
像这样设置视图引擎。
app.set('view engine', 'html');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index');
});
第二个选项是不需要设置视图引擎。
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/about.html');
});
您需要使用npm命令来启动服务器
npm start