Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
Node app has an HTML page call another JavaScript file? Uncaught SyntaxError: Unexpected token '<'

Simple setup question here. I have my node project which has opened a localhost server running an html page. From that html page, how can I call another script?

index.js

var http = require('http');
var fileSystem = require('fs');

var server = http.createServer(function(req, resp){
    fileSystem.readFile('./main.html', function(error, fileContent){
        if(error){
            resp.writeHead(500, {'Content-Type': 'text/plain'});
            resp.end('Error');
        }
        else{
            resp.writeHead(200, {'Content-Type': 'text/html'});
            resp.write(fileContent);
            resp.end();
        }
    });
});

server.listen(8080);

console.log('Listening at: localhost:8080');

main.html

<!DOCTYPE html>
<html lang="en">
    <body>
        <p>Hello world! Node is awesome, is it not?</p> 
        <script src="new_script.js"></script>   
    </body>
</html>

This page shows the <p> text and runs on localhost:8080, then gives the error in console Uncaught SyntaxError: Unexpected token '<'

This is the new_script.js which is not running:

alert("new_script.js called");
test1 = 123; test2 = 543; 
test3 = test1*test2;
alert(test3);

And my file folder structure is flat, everything is there:

enter image description here

So how can I get started calling more JavaScript into my loaded up html page on my node.js server?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your current web site at localhost:8080 will do nothing but serve out a Html page with the contents of main.html, for all request paths. So the call to localhost:8080/new_script.js, the file referenced in your main page, will also be returned the contents of your main.html and not the contents of that new_script.js file. The first occurrence of the < character in your main.html probably explains that error message.

Unless you are doing this for purely academic purposes, you should be using something like Express if you want to code a real web site.

If you really want to do this with plain Node, then you have to parse and handle every url on the request object. You have to do something rather laborious such as:

var server = http.createServer(function(req, resp){
    if (req.url === "/") {
        fileSystem.readFile('./main.html', function(error, fileContent){
            if(error){
               resp.writeHead(500, {'Content-Type': 'text/plain'});
               resp.end('Error');
            }
           else{
               resp.writeHead(200, {'Content-Type': 'text/html'});
               resp.write(fileContent);
               resp.end();
            }
        });
    } else if (req.url === "/new_script.js") {
        fileSystem.readFile('./new_script.js', function(error, fileContent){
            if(error){
               resp.writeHead(500, {'Content-Type': 'text/plain'});
               resp.end('Error');
            }
           else{
               resp.writeHead(200, {'Content-Type': 'text/javascript'});
               resp.write(fileContent);
               resp.end();
            }
        });
    } else {
       resp.writeHead(404);
       resp.end("Not found");
    }
});
about 4 years ago · Juan Pablo Isaza Relatório

0

(Posted solution on behalf of the question author, to move it to the answer space).

This got resolved by using Express.js, which is really convenient.

npm install express --save

index.js:

const express = require('express')
const app = express()
const port = 3000

app.use(express.static("./js"));

app.get('/', (req, res) => {
  //res.send('Hello World!')
  res.sendFile('./main.html', { root: __dirname });
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Now all the code is the same, except I'm telling the project to use the folder "js/" to find JavaScript files. So I just moved new_script.js in there and it works :)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda