NodeJS + Express提供的HTML文件无法加载js文件? [英] NodeJS + Express served HTML file not loading js file?
问题描述
我正在运行一个NodeJS服务器,该服务器使用综合路由来提供文件'index.html'.在该文件中,我链接到同一目录中的javascript文件.该javascript文件未正确加载.我的控制台中的错误显示为未捕获的SyntaxError:意外的令牌<",这在研究后似乎意味着我的JS文件的路径不正确.但是,该js文件与"index.html"位于同一目录中,我正在像这样引用它,哪个应该正确?
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?
这是我的代码
server.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
<!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
console.log('test.js loaded');
推荐答案
您应该这样设置静态文件夹
You should set your static folder like this
app.use(express.static(__dirname + '/public'));
此外,您的html文件还将在/public文件夹中查找脚本文件.您需要为index.html文件提供脚本文件的正确路径.
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.
<script src="/app/views/test.js"></script>
这篇关于NodeJS + Express提供的HTML文件无法加载js文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!