When I run my Express code from Postman, everything works perfectly. However, when I try to call it from Mocha, I encounter issues specifically with setting data in the header of a POST request. This problem only occurs with POST requests containing parameters, as GET and parameterless POST requests function as expected.
Below is the simplified code snippet that functions correctly in 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);
})
Here is the example of what Postman sends:
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"
}
and here is the excerpt showing how it's handled in Mocha:
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);
});
The response received is The undefined is undefined.
I'm seeking assistance in identifying where I am going wrong or even tips on how to troubleshoot this issue?