Cada vez que ejecuté este servidor de nodo en el puerto "8000"
const http=require('https') const PORT=8000 const server=http.createServer() server.on('request',(req,res)=>{ if (req.url==='friend'){ res.writeHead(200,{ 'Content-Type':'text/plain', }) res.end(JSON.stringify({ id:1, name:'Sir Issac Newton', })) } if (req.url==='foe'){ res.writeHead(200,{ 'Content-Type':'text/plain', }) res.end('The Enemy is Ego Bro') } }) server.listen(PORT,()=>{ console.log(`the respnse is exectued at ${PORT}`) })me sale un error en el Borwser que dice:
localhost no envió ningún dato. ERR_EMPTY_RESPONSE
Trato de cambiar los puertos, pero aún muestra este error. Por favor, ¿qué debo hacer y explíqueme cuál es este error? ¡Gracias!
Este código tiene 3 problemas.
Debe cambiar const http=require('https') a const http=require('http') . Si desea utilizar HTTPS, consulte el documento de nodejs para saber cómo configurar el servidor https
En nodejs, la URL de solicitud HTTP comienza con / y su declaración de condición no funciona
Porque la URL de solicitud no coincide con el servidor de declaración de condición no responde nada y ocurre este error.
Deberías cambiar el código así:
const http=require('http') const PORT=8000 const server=http.createServer() server.on('request',(req,res)=>{ if (req.url==='/friend'){ res.writeHead(200,{ 'Content-Type':'text/plain', }); res.end(JSON.stringify({ id:1, name:'Sir Issac Newton', })); return; } if (req.url==='/foe'){ res.writeHead(200,{ 'Content-Type':'text/plain', }); res.end('The Enemy is Ego Bro'); return; } res.writeHead(400,{ 'Content-Type':'text/plain', }); res.end('URL not match'); }) server.listen(PORT,()=>{ console.log(`the respnse is exectued at ${PORT}`) })