我正在尝试用Express Node.js成功地呈现索引文件,但是如果我使用带参数的名称空间,没有参数则呈现嫩枝文件并包含自己的脚本,如果我使用带参数的try,呈现ok bu脚本文件路径问题,所以html中头部的脚本文件不能包含而路径不正确
例如,如果没有参数,html文件style.css看起来像路径http://127.0.0.1:3000/style.css
使用参数时,html文件style.css看起来像路径http://127.0.0.1:3000/mynamespace/style.css<--没有找到!
说找不到浏览器路径!
server.js
const port = 3000;
const express = require('express');
const app = express();
const http = require('http');
const socketIO = require('socket.io');
const server = http.Server(app);
server.listen(this.port, () => {
console.log(`Server running on: http://127.0.0.1:${port}`);
});
const io = socketIO(server);
app.set('view engine', 'twig');
app.set('views', "views");
app.use(express.static('public'));
app.use(express.static('scripts'));
app.use(express.static("styles"));
/// Routing
/**
* This work fine
* Render client.twig
* Including Scripts in head
*/
app.get('/mynamespace', function (req, res, next) {
res.render("client");
});
/**
* This work with error
* Render client.twig
* don't Including Scripts in head
*
*/
app.get('/mynamespace/:id', function (req, res, next) {
res.render("client");
});
io.of("/mynamespace").on('connection',(socket)=>{
socket.on('online_users', (data) => {
console.log(`Online Users ${data}`);
});
});
client.js
let url = `http://127.0.0.1:3000/mynamespace`;
console.log("Url", url);
this.socket = io(url);
this.socket.on("connect", ()=>{
try{
this.socket.emit('welcome', {
message:"Welcome guest"
});
} catch (e) {
alert(e.message);
}
});
Client.Twig
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/>
<title>RestoCommend</title>
<script src="/socket.io/socket.io.js"></script>
<link rel="stylesheet" href="style.css"
</head>
<body>
<h3>Client</h3>
<script src="helper.js"></script>
<script src="client.js"></script>
</body>
</html>
听起来您希望在相对路径下服务静态文件。请尝试以下操作:
app.use('/mynamespace', express.static('public'))
app.use('/mynamespace', express.static('scripts'))
app.use('/mynamespace', express.static('styles'))
而且还
<link rel="stylesheet" href="mynamespace/style.css" />
从您的代码来看,style.css
文件与client.twig
位于同一个目录中,后者是views
目录。但是您已经告诉express静态目录是public
,scripts
和styles
。没有指示express知道从哪里提供css。尝试将style.css文件移动到styles目录中。
祝你好运。