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

124
Views
Codificación de datos JSON POST en prueba Mocha de código Express

Mi código Express funciona bien cuando se llama desde Postman, pero no cuando se llama desde Mocha. Esto me lleva a creer que mi prueba de Mocha no está configurando correctamente los datos en el encabezado de una solicitud POST (no tengo ningún problema con GET o POST sin parámetros, ni con GET con parámetros; solo con POST con parámetros).

Aquí está el código simple, aunque no me concentraría en esto, ya que funciona desde Postman:

 const app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // Our unit tests send POST data in JSON format app.use(express.json()); // Helper function - common code function ResplyWithSentence(object, adjective) { console.log('GET requestuest received: object = ' + object + '; adjective = ' + adjective); let sentence = softwareUnderTest.MakeAsentence(object, adjective); sentence = JSON.stringify(sentence); response.status(200); response.set('Content-Type', 'text/json'); response.send( sentence ); } // Handling POST request with parameters app.post("/makeSentenceParamsPost", (request, response) => { const object = request.body.object; const adjective = request.body.adjective; ResplyWithSentence(object, adjective); })

Esto es lo que envía Postman:

 POST /makeSentenceParamsPost HTTP/1.1 Host: localhost:3000 Content-Type: application/json Cache-Control: no-cache Postman-Token: 88dfc7cc-427e-3248-ba93-286083d4c18d { "object": "cat", "adjective": "sleepy" }

y aquí está el moka:

 it('should handle a POST request with parameters', async function(){ var xhttp = new XMLHttpRequest(); xhttp.open("POST", "http://localhost:3000/makeSentenceParamsPost", false); // false === synchronous/blocking xhttp.setRequestHeader("Content-type", "application/json"); const object = 'hubris'; const adjective = 'pervasive'; let postParameters = {'object': object, 'adjective': adjective}; xhttp.onreadystatechange = function(done) { while(this.readyState != 4) ; // wait until "request finished and response is ready" assert.isObject(this); assert(this.status == 200); assert(JSON.parse(this.responseText)['sentence'] == `The ${object} is ${adjective}`); done(); }; postParameters = JSON.stringify(postParameters); xhttp.send(postParameters); });

La respuesta recibida es The undefined is undefined.

¿Alguien puede decirme qué estoy haciendo mal? ¿O incluso cómo depurar esto?

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

0

¡Usa JavaScript moderno!

Sugeriría buscar en fetch. Es el equivalente de ES5 y usa Promises. Es mucho más legible y fácilmente personalizable.

 const fetch = require("node-fetch"); const first = 'hubris'; // can't use words like object, these are reserved. const second = 'pervasive'; let postParameters = {'first': first, 'second': second}; const url = "http://example.com"; fetch(url, { method : "POST", body: postParameters, // -- or -- // body : JSON.stringify({ // user : document.getElementById('user').value, // ... // }) }).then( response => response.text() // .json(), etc. assert.isObject(this); assert(this.status == 200); assert(JSON.parse(this.responseText)['sentence'] == `The ${object} is ${adjective}`); done(); );
about 4 years ago · Juan Pablo Isaza Report

0

Mayúscula T en Tipo resuelve el problema:

 xhttp.setRequestHeader("Content-Type", "application/json");
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!