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

132
Views
Cómo obtener datos de front-end en el backend usando Vanilla Node Js

Sé que es posible obtener datos enviados por el usuario en el back-end usando Express.js, que es:

 router.get("/pathName", async function(req, res){ count = req.body; })

Pero, ¿cómo hacer esto en Vanilla (puro) Node.js?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Aquí hay un ejemplo de un servidor simple.

 const http = require('http'); http .createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html', }); switch (req.url) { // http://localhost:8080/ case '/': res.write('<h1>Home</h1>'); break; // http://localhost:8080/page case '/page': res.write('<h1>Page</h1>'); break; } res.end(); }) .listen(8080);

Además, aquí hay un ejemplo (probablemente incompleto en términos de todos los casos extremos...) de cómo obtener datos JSON de una carga útil de solicitud:

 const http = require("http"); // server that only supports POST /count // expects JSON data to be passed like { "count": 100 } // must have application/json content type header and POST method http .createServer(async (req, res) => { // ensure method is content type json, POST, and /count if ( req.headers["content-type"] != "application/json" || req.url !== "/count" || req.method !== "POST" ) { res.writeHead(404, { "Content-Type": "application/json", }); res.write(JSON.stringify({ message: "Unsupported route" })); res.end(); } // try to read body let body; try { body = await readBody(req); } catch (err) { res.writeHead(400, { "Content-Type": "application/json", }); res.write(JSON.stringify({ message: err.message })); res.end(); } // try to parse body let parsedBody; try { parsedBody = JSON.parse(body); } catch (err) { res.writeHead(400, { "Content-Type": "application/json", }); res.write(JSON.stringify({ message: err.message })); res.end(); } // make sure count property is present in parsed body if (typeof parsedBody.count === "undefined") { res.writeHead(400, { "Content-Type": "application/json", }); res.write(JSON.stringify({ message: err.message })); res.end(); } // create response res.writeHead(200, { "Content-Type": "application/json", }); res.write(JSON.stringify({ message: "Got " + parsedBody.count })); res.end(); }) .listen(8080); function readBody(req) { return new Promise((res, rej) => { let body = ""; req.on("data", (data) => { body += data; }); req.on("end", () => { res(body); }); req.on("error", (err) => { rej(err); }); }); }

Genial para ver cómo funciona para el aprendizaje. Pero si lo está utilizando para un proyecto, le recomiendo Express u otro marco/lib, ya que encontrará que será bastante doloroso tratar de considerar todos los casos que necesitará. Los marcos como Express son bastante ligeros de todos modos.

about 4 years ago · Juan Pablo Isaza 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!