我做前端所以当我试图在服务器上做某事时,我有时会迷失方向。
我有这个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;
..和这个字符串模板
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和脚本文件不起作用
你能看出我做错了吗?
答案 0 :(得分:1)
假设您的server.js文件和您的公共目录存在于同一级别,path.resolve(__dirname, 'public')
将构建公共目录的完整路径,其中应存在所有静态资源。在HTML页面中引用这些文件时,请指定相对于公共目录的路径。
<link href="css/main.css"/>
这应该足以找到该文件。假设该文件存在于../public/css/main.css
。