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

253
Visualizações
How serve client javascript modules in node.js

I'm new programmer to node.js. I trying to create vanilla server in node.js. In my client, I used ES6 modules. when I start my server and search for http://localhost:3000/ in my browser, HTML and CSS loaded but for javascript have this error:

enter image description here

I have four javascript modules for client side and in HTML I use this code for load javascript moduls:

<script type="module" src="js/controller.js" async></script>

My server code :

const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = 3000;
const server = http.createServer();

server.on('request', (req, res) => {
    let routes = {
        'GET': {
            '/': indexHtml,
        }
    }
    console.log(req.url)
    let handler = routes[req.method][req.url];

    handler = handler || readFile;
    handler(req, res);
})

server.listen(PORT, () => {
    console.log(`Listening on port ${PORT}...`)
});

function indexHtml(req, res) {
    readFile({ url: '/index.html' }, res);
}

function readFile(req, res) {
    var filePath = path.join(__dirname, '../client/', req.url);
    // console.log(filePath)
    fs.readFile(filePath, (error, data) => {
        if (error) {
            res.writeHead(404);
            res.write('Not found error 404');
            res.end()
        } else {
            res.writeHead(200);
            res.write(data);
            res.end();
        }
    })
}

How can I solve this error and serve javascript modules, Thanks a lot for your help.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

With comment @derpirscher, I change my reader function with this code :

function readFile(req, res) {
    var filePath = path.join(__dirname, '../client/', req.url);

    fs.readFile(filePath, (error, data) => {
        if (error) {
            res.setHeader('Content-Type', 'text/html');
            res.writeHead(404);
            res.write('Not found error 404');
            res.end()
        } else {
            const url = req.url === '/' ? '/index.html' : req.url;
            if (req.url.includes('js')) res.setHeader('Content-Type', 'application/javascript');
            if (req.url.includes('css')) res.setHeader('Content-Type', 'text/css');
            if (req.url.includes('html')) res.setHeader('Content-Type', 'text/html');
            res.writeHead(200);
            res.write(data);
            res.end();
        }
    })
}
over 4 years ago · Santiago Trujillo 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