• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

182
Vistas
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.

about 3 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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();
        }
    })
}
about 3 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda