SOUPTIK BANERJEE
SOUPTIK BANERJEE

Reputation: 183

Axios request forward code converts json to buffer when responding to original call

I have a nodejs service gateway code that forwards requests to services made by an Angular app. Here is a piece of that code

router.get('/callService/:service/*', (req, res) => {
    certOption = { httpsAgent: new https.Agent({ ca: fs.readFileSync(config.get("sslCertFilename")) }) };
    let serviceName = req.params.service;
    let serviceRoute = req.params[0];

    let authHeaders = {
        "Authorization": req.headers["authorization"],
        "subscriber-id": req.headers["subscriber-id"],
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
    }

    axios.get(`${config.get(serviceName)}/${serviceRoute}`, Object.assign(certOption, {
        params: req.query,
        headers: authHeaders
    }))
    .then(function (response) {
        // handle success
        res.json(response.data);
    })
    .catch(function (error) {
        // handle error
        console.log(error);
        if (error.response)
            res.status(error.response.status).json(error.response.data);
        else
            res.status(500).send();
    });
});

The app is used as follows: Angular App (A) calls NodeJS Gateway (N) which in turn calls Service (S) and returns the response from S to A.

99% of the time the code works as expected and has been working for over a year now. Suddenly since last month intermittently an issue pops up where instead of returning the JSON from S to A it returns an buffer object {"type":"Buffer","data":[...]}. When I parse the buffer it gives me the JSON actually returned from S. When I restart the service it starts working again. I am not able to figure out the issue behind it.

Any help is appreciated

Upvotes: 2

Views: 971

Answers (1)

SOUPTIK BANERJEE
SOUPTIK BANERJEE

Reputation: 183

Turns out that the solution was to enforce the responseType: 'json' header in the request. I have one request that uses responseType: 'arraybuffer' and that affects the other requests when the app is under stress.

Upvotes: 1

Related Questions