Rex*_*xha 1 javascript node.js express
我想在我的 html 文件中加载客户端 javascriptchat.js和 css style.css,但404在加载它们时出现错误。
这是我的服务器文件:
// routing
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
Run Code Online (Sandbox Code Playgroud)
这是我的客户端 html:
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="chat.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
Run Code Online (Sandbox Code Playgroud)
如何在我的应用程序中加载它们?所有文件都在同一个根文件夹中。我试过这个,但它不起作用:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/chat.js');
});
Run Code Online (Sandbox Code Playgroud)
看起来您正在使用 express Web 框架,因此在这种情况下,您应该出于您的目的使用express 静态中间件。
我做了一个下面的例子。
这是服务器server.js文件:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(4040, function() {
console.log('server up and running');
});
Run Code Online (Sandbox Code Playgroud)
您可以看到 Express 正在为驻留在public目录中的文件提供服务。你看我没有提供路由,/因为浏览器会自动抓取index.html.
public/index.html:
<!doctype html>
<html>
<head>
<link href="style.css" rel="stylesheet"/>
</head>
<body>
<h1>Hey</h1>
<script src="app.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
从他只知道浏览器的角度来看index.html,app.js和style.css文件,因为他们被明确规定。
public/style.css:
body {
background: red;
}
Run Code Online (Sandbox Code Playgroud)
public/app.js
document.addEventListener('DOMContentLoaded', function() {
alert('hello world');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1469 次 |
| 最近记录: |