Joshua Bakker Joshua Bakker - 5 months ago 48
Node.js Question

Node.JS add script tag

I am trying to create something in Node.JS. I got the server started and a request to index.html. In index.html I got this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="name" placeholder="name">
<button id="login">Login</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="/scripts/main.js"></script>
</body>
</html>


In my scripts/main.js file I got this:

var socket = null;

$(document).ready(function() {
$('#login').click(login);
});

function login()
{
socket = io();

socket.emit('set-name', {name: $('#name').val()});
};


In my app.js:

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

app.use('/scripts', express.static(__dirname + '/scipts/'));


Where

var app = require('express')();


However, my browser complains that main.js file isn't found... I don't have much experience with it, so how can I fix this?

This is my project structure:

Project structure

Answer

Replace app.use('/scripts', express.static(__dirname + '/scipts/')); with app.use('/scripts', express.static(__dirname + '/scripts/'));

For path concatenation please consider to use path.join as environment independent method.

Comments