gpt4 book ai didi

javascript - 在 Node.js 中加载客户端 Javascript 和 CSS

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:44 24 4
gpt4 key购买 nike

我想在我的 html 文件中加载客户端 javascript chat.js 和 css style.css,但在加载它们时出现 404 错误。

这是我的服务器文件:

// routing
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});

这是我的客户端 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">

如何将它们加载到我的应用程序中?所有文件都位于同一根文件夹中。我尝试了这个,但它不起作用:

app.get('/', function (req, res) {
res.sendFile(__dirname + '/chat.js');
});

最佳答案

看起来您正在使用 Express Web 框架,因此在这种情况下您应该使用 express static middleware为了您的目的。

我做了一个下面的例子。

这是服务器 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');
});

您可以看到 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>

从浏览器的 Angular 来看,他只知道 index.htmlapp.jsstyle.css 文件,因为它们是由express提供的。

<小时/>

public/style.css:

body {                                                          
background: red;
}
<小时/>

public/app.js

document.addEventListener('DOMContentLoaded', function() {
alert('hello world');
});

关于javascript - 在 Node.js 中加载客户端 Javascript 和 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31278682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com