在express.js中使用htmlstring来提供静态文件

我做了前端,所以当我试图在服务器上做某些事情时,我有时会迷失方向。

我有这个server.js文件

const express = require('express'); const http = require('http'); const path = require('path'); const logger = require('morgan'); const renderPage = require('./layout'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const admin = require("firebase-admin"); var index = require('./routes/index'); // Initialize the Express App const app = express(); // Apply body Parser and server public assets and routes app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.resolve(__dirname, 'public'))); app.use('/', index); app.use((req, res, next) => { res .set('Content-Type', 'text/html') .status(200) .end(renderPage()); }); var server = http.createServer(app); // start app server.listen(3000); module.exports = app; 

..和这个string模板

 const renderPage = (initialState) => { return ` <!DOCTYPE html> <html> <head> <link href="public/css/main.css"/> <script src="some external javascript"/> </head> <body> <div id="app"></div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; </script> </body> </html> `; }; module.exports = renderPage; 

当我启动服务器,它的工作原理,但CSS和脚本文件不起作用

你能看到我做错了吗?

假设你的server.js文件和你的公共目录存在于同一级别,那么path.resolve(__dirname, 'public')将构build公共目录的完整path,所有你的静态资源应该存在。 当您在HTML页面内引用这些文件时,可以指定相对于公用目录的path。

 <link href="css/main.css"/> 

这应该足以find该文件。 假设该文件存在../public/css/main.css