javascript NodeJS + Express 提供的 HTML 文件未加载 js 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31622394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:04:35  来源:igfitidea点击:

NodeJS + Express served HTML file not loading js file?

javascripthtmlnode.jsexpress

提问by JohnWick

I am running a NodeJS server which uses a catchall route to serve a file 'index.html'. In that file, I am linking to a javascript file in the same directory. That javascript file is not being correctly loaded. The error in my console reads 'Uncaught SyntaxError: Unexpected Token <', which after researching seems to mean that the path to my JS file is incorrect. However, the js file is located in the same directory as 'index.html', and I am referencing it like so which should be correct?

我正在运行一个 NodeJS 服务器,它使用一个包罗万象的路由来提供文件“index.html”。在该文件中,我链接到同一目录中的 javascript 文件。该 javascript 文件未正确加载。我的控制台中的错误显示为“Uncaught SyntaxError: Unexpected Token <”,经过研究,这似乎意味着我的 JS 文件的路径不正确。但是,js 文件与“index.html”位于同一目录中,我像这样引用它,哪个应该是正确的?

Here is my code

这是我的代码

server.js

服务器.js

var express = require('express');
var app = express();
var config = require('./config');
var apiRouter = express.Router();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var User = require('./app/models/User');
var jwt = require('jsonwebtoken');
var path = require('path');

//Set the public folder
app.use(express.static('/public'));

//Allows us to parse POST data.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

mongoose.connect(config.db);

var apiRouter = require('./app/routes/api')(app, express);

app.use('/api', apiRouter);

//MEAN apps use a catchall after any routes created by Node.

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

app.listen(1337);

console.log('Server started at ' + Date());

public/app/views/index.html

公共/应用程序/视图/index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="./test.js"></script>
<head>
<body>
    <h1>Served by node + express.</h1>
</body>
</html>

public/app/views/test.js

公共/应用程序/视图/test.js

console.log('test.js loaded');

回答by Bidhan

You should set your static folder like this

你应该像这样设置你的静态文件夹

app.use(express.static(__dirname + '/public'));

Also, your html file will look inside the /public folder itself for your script file. You'll need to give your index.html file the right path to your script file.

此外,您的 html 文件将在 /public 文件夹中查找您的脚本文件。您需要为 index.html 文件提供脚本文件的正确路径。

<script src="/app/views/test.js"></script>

回答by mscdex

Here's what's happening:

这是发生了什么:

  • The browser requests /, which is responded to by your catchall route, so it gets back index.html.

  • The browser then sees a script in the html at ./test.js, so the browser then interprets that as /test.jsand makes a request for that. The express.staticmiddleware looks up public/test.js, which does not exist, so it passes execution to the next defined route that matches the request, which is your catchall route. This means html is sent for the javascript file, hence the error that you see.

  • 浏览器请求/,由您的通用路由响应,因此它返回index.html

  • 然后浏览器在 html 中看到一个脚本./test.js,因此浏览器将其解释为/test.js并发出请求。该express.static中间件抬头public/test.js,这不存在,所以它传递到执行的请求,这是你的包罗万象的路由匹配下一个定义的路径。这意味着 html 是为 javascript 文件发送的,因此您会看到错误。

So to fix this, you need to change ./test.jsto the actual relative path (./app/views/test.js) or use an absolute path (/app/views/test.js) to make sure the correct path is always used, no matter what the current path is.

因此,要解决此问题,您需要更改./test.js为实际的相对路径 ( ./app/views/test.js) 或使用绝对路径 ( /app/views/test.js) 以确保始终使用正确的路径,无论当前路径是什么。

Additionally, you will need to change this:

此外,您需要对此进行更改:

app.use(express.static('/public'));

to something like this:

到这样的事情:

app.use(express.static(__dirname + '/public'));

Otherwise the express.staticmiddleware will look for a directory named publicoff the root of your filesystem and you will have the same problem with the catchall route serving html for your javascript file request.

否则,express.static中间件将查找以public文件系统根目录命名的目录,并且您将遇到与为您的 javascript 文件请求提供 html 的 catchall 路由相同的问题。