我知道標準方法是使用 Express,但我想知道如何在不使用它的情況下實作這一點。我已經知道如何通過 nodejs 在公共網站(沒有前端框架)中使用 http/https 提供 html 檔案,但是當我嘗試使用 React 應用程式中的 index.html 執行相同操作時,它不起作用。我認為重要的是要提到我正在使用 react-router。我對此進行了很多搜索,但每個教程都會使用 Express,因此我無法在 google 中找到幫助。
這是我將如何處理純 html:
const server = http.createServer( async (req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
const requestUrl = url.parse(req.url);
let completePath = requestUrl.pathname;
let path = completePath.split('/').slice(1)[0];
let fileContent;
if(path == "")
path = "index.html";
try{
fileContent = fs.readFileSync(path);
res.end(fileContent, 'utf-8');
}
catch(err){
console.log("File not found: " path);
if(path != "favicon.ico"){
res.statusCode = 404;
fileContent = fs.readFileSync("404.html");
res.end(fileContent);
}
}
});
謝謝!
uj5u.com熱心網友回復:
好的,我終于明白了:
const fs = require('fs');
const https = require('http');
const hostname = 'localhost';
const port = 3000;
const server = https.createServer( async (req, res) => {
res.statusCode = 200;
let root = "./build";
let path = root req.url;
let fileContent;
if(path == root "/")
path = path "index.html";
try{
fileContent = fs.readFileSync(path);
res.end(fileContent, 'utf-8');
}
catch(err){
if(req.url != "/favicon.ico"){
fileContent = fs.readFileSync(root "/index.html");
res.end(fileContent);
}
}
});
server.listen(port, hostname, () => {
console.log("Server listening on " port);
});
與 Express 版本相反:
const express = require("express");
const app = express();
// this throws everything to the user
app.use(express.static(__dirname "/build"));
// this redirects everything to index.html
app.get('*', (req, res) => {
res.sendFile(__dirname "/build/index.html");
});
app.listen(port, hostname, () => {
console.log("Server listening on " port);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/388148.html
