Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
Cómo servir los módulos javascript del cliente en node.js

Soy nuevo programador en node.js. Intento crear un servidor Vanilla en node.js. En mi cliente, usé módulos ES6. cuando inicio mi servidor y busco http://localhost:3000/ en mi navegador, HTML y CSS están cargados pero para javascript tengo este error:

ingrese la descripción de la imagen aquí

Tengo cuatro módulos de javascript para el lado del cliente y en HTML uso este código para cargar módulos de javascript:

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

Mi código de servidor:

 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(); } }) }

¿Cómo puedo solucionar este error y servir módulos de javascript? Muchas gracias por su ayuda.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Con el comentario @derpirscher, cambio mi función de lector con este código:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!