Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  9] [ 5]  / answers: 1 / hits: 17266  / 9 Years ago, sat, july 25, 2015, 12:00:00

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');

More From » html

 Answers
14

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>

[#65683] Thursday, July 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaydon

Total Points: 651
Total Questions: 103
Total Answers: 100

Location: Norway
Member since Mon, May 23, 2022
2 Years ago
;