Node.js提供HTML,但无法在提供的页面中加载脚本文件 [英] Node.js serve HTML, but can't load script files in served page

查看:161
本文介绍了Node.js提供HTML,但无法在提供的页面中加载脚本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mongoDB数据库和Node.js + express创建一个小的登录页面。我是Node.js的新手,所以解决方案可能比我想象的要容易。
问题是:当我连接到服务器页面时提供HTML文件时,我无法使用html文件中引用的JavaScript文件。我该如何解决?
Ps index.html和client.js文件都位于名为client的文件夹中。

i'm trying to make a little login page using a mongoDB database and Node.js + express. I'm new to Node.js so maybe the solution is easier than i thought. The problem is: when i serve the HTML file when connecting to the server page, i can't use the JavaScript file referenced in the html file. How can i fix it? P.s the index.html and client.js files are all located in a folder named "client".

代码:

var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(__dirname + 'client'));
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/client/index.html'));
});

HTML文件:

 <!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Login</title>
    <meta name="description" content="Login Page">
    <meta name="author" content="AlbertoCoder">
    <script src="/client/client.js"></script>
</head>
<body>
</body>
</html>


推荐答案

你可以使用它,但你需要通过有效路径从您的服务器提供该javascript文件。

You're able to use it, but you need to serve that javascript file from your server through a valid path.

在您的HTML中,您试图从 / client /中检索javascript文件client.js

In your HTML you're trying to retrieve the javascript file from /client/client.js

这里的提示是:

想象一下服务器的以下URL http:// myserver:8080 /

Imagine the following URL of your server http://myserver:8080/

现在,您的HTML是试图通过 http:// myserver:8080 / client / client.js检索js文件

Now, your HTML is trying to retrieve the js file through http://myserver:8080/client/client.js

当你可以看到,您的服务器没有提供该资产,因此您将无法检索该js文件。

As you can see, your server is not serving that assets, thus you won't be able to retrieve that js file.

执行以下操作:

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

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

这篇关于Node.js提供HTML,但无法在提供的页面中加载脚本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆