TransWikia.com

Issues with linking Javascript files with Node.js and HTML

Stack Overflow Asked by Coder Husk on December 29, 2020

I am making an application with node.js and I basically want render a canvas with node.js so I can access a json file on the server since you can’t change client storage on browsers. To add on when running my files I get this weird syntax error.

Uncaught SyntaxError: Unexpected token '<'

Further examination shows that my javascript files that I am requiring (see internals folder) are being overwritten with html, thus causing the error. My question is why is it overwritting only the files I am requiring from the html I am rendering? To add on I am running on a dynamic port (65535) and on a localhost (client). My code is here

2 Answers

This is because you are sending the index.html file for all requests in your app.js file, ignoring the request URL.

You need to properly serve the JS files. You can take a look here for more details: https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/

Answered by Seblor on December 29, 2020

Your node server is not serving your static files, it only serves one html.

You might need to set up a static file server like or programm you server to lookup GET /internals/render.js and scaleCanvas.js

You can use express for that, it has all this out of the box.

https://expressjs.com/en/starter/static-files.html

var app, server,
    express = require('express'),
    path = require('path'),
    host = process.env.HOST || '127.0.0.1',
    port = process.env.PORT || 3000,
    root = path.resolve(__dirname, '..');
 
app = express()
app.use(express.static(root + '/public'));
server = app.listen(port, host, serverStarted);
 
function serverStarted () {
    console.log('Server started', host, port);
    console.log('Root directory', root);
    console.log('Press Ctrl+C to exit...n');
}

Answered by uke on December 29, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP