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?
Here is my code
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 put all javascript code in a <script> tag for the browser to recognize and make it run and for the src attribute of the script tag to find your 'script. js' file, it just has to be in the same directory as the html file, you don't need to specify the entire file root.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
For html page we have to use URL so for that in Node JS “url” module has been used so we have to add this module in our program file. And then we can get the path of request URL as shown below. var url=require("url"); var path=url.
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.
<script src="/app/views/test.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With