Have you ever tried to return custom HTTP headers from your SailsJS backend REST API to your frontend AngularJS application and wondered why they don’t show up in AngularJS?
I had pretty standard case where I wanted to implement server side pagination for my data sets returned by the API. For that you need to return the total number of records in order to implement pagination properly in the frontend. I decided to return the total number of records in a custom header called “X-TotalRecords”. It is returned together with the response but it didn’t show up in AngularJS response:
..... .then(function(response){ $log.debug(response.headers()) //does not show my custom header }) .....
After some googling around I found a solution. You need to create a custom SailsJS policy and send a special header “Access-Control-Expose-Headers” there. Let’s call the policy sendCorsHeaders.
Create a file sendCorsHeaders.js in policies/ folder:
module.exports = function (req, res, next) { res.header('Access-Control-Expose-Headers', sails.config.cors.headers); next(); };
As you can see it re-uses headers defined in your cors.js under config/ folder.
From now on you can retrieve your custom header in AngularJS $http service.
Follow me: byShare me: by