Monday, March 20, 2017

Express.js http call inside route doesn't update variable

Leave a Comment

I'm building a REST api on top of express.js. I am having trouble updating variables inside my routes.

Example:

I'm calling app.get("/wp/page/create/:id", function(req, res)

Inside this route I start by calling a http request using request-promise library. The response of this call I use in a nested http call.

I use a global variable for the headers for the nested call, and it's to the header a i need to make changes by using the etag variable.

Code:

global.postHeaders = headers; postHeaders['X-HTTP-Method'] = "MERGE"; postHeaders['Content-Type'] = 'application/json;odata=verbose'; postHeaders['X-RequestDigest'] = spContext;  request.get({ url: "xxx", headers: headers, json: true }).then(function(response) {     var etag = response.d.__metadata.etag     postHeaders['If-Match'] = etag;      request.post({        url: "xxx",        type: "POST",        body: data,        headers: postHeaders,        json: true        }).then(function(data) {           res.send(data).end()           console.log("All done!");       }) }) 

When i start the server up and enter the route everything works fine. When i when try to hit it again the etag variables is still the same, even though it should be updated.

If I restart the server it works the again on the first attempt but fails on the second/third.

Any idea what I am doing wrong?

2 Answers

Answers 1

I have resolved the issues. The simple solution was to clear the headers containing the variable.

global.postHeaders = headers; postHeaders['X-HTTP-Method'] = "MERGE"; postHeaders['Content-Type'] = 'application/json;odata=verbose'; postHeaders['X-RequestDigest'] = spContext;  request.get({  url: "xxx",  headers: headers,  json: true  }).then(function(response) { var etag = response.d.__metadata.etag postHeaders['If-Match'] = etag;     request.post({      url: "xxx",      type: "POST",      body: data,      headers: postHeaders,      json: true      }).then(function(data) {       postHeaders['If-Match'] = "";       res.send(data).end()       console.log("All done!");   }) }) 

Answers 2

postHeaders is a global variable. is headers in global.postHeaders = headers; also a global varaible ? Whatever you are trying to do here is grossly wrong. postHeaders variable will be shared across multiple request. so you will hit a scenario where postHeaders['If-Match'] value might be empty string or the etag .

Try this instead of the first line var postHeaders = Object.assign({}, headers);

Not sure what you are trying, but at-least this statement will subside the huge error in the code. This will create a new header object for each request.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment