[英]NodeJS - Trying to render index.ejs file, but still only servers index.html that is in my public folder
[英]nodejs : My /public/index.html file does not appear on the screen
|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項目沒有出來。
[公共>索引.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');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.