How to do it...

Let's walk through reading and writing headers in Express to implement CORS headers and language locale preferences using the Accept-Languages header:

  1. First, in our /routes/api.js route configuration, we will add a new route for any incoming options requests. We will want to add this route before any other API routes in this configuration file so that it is handled first:
...
router.options('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods',
'GET,PUT,POST,DELETE,PATCH,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-
Type, Authorization, Content-Length, X-Requested-
With');
res.send(200);
});
...
  1. Now, when API requests make pre-flight requests to our API, their client will allow them to make normal requests even if the API is on a different domain than the client.
  2. Next, we will enhance our /routes/angular.js route configuration to load our Angular application's index.html file into memory when the web server starts. We will then preparse the contents in cheerio so that they are ready for us to use in our wildcard route:
var path = require('path');
var fs = require('fs');

var express = require('express');
var router = express.Router();

var cheerio = require('cheerio');
var angularBuildPath = path.resolve(__dirname,
'../../my-angular-project/dist');
var angularIndexFile = cheerio.load(
fs.readFileSync(
path.join(angularBuildPath, 'index.html'),
{encoding: "utf8"}
)
);
...
  1. Now, we will update our wildcard route to parse out the locale property from the incoming Accept-Language header and insert it into our document.locale script tag in the header of our index.html:
...
router.use(express.static(angularBuildPath));

router.get('*', (req, res, next) => {
if (req.url.startsWith('/api')) return next();
var locale = req.get('Accept-Language').split(',')[0];
angularIndexFile('head script').html('document.locale = "' + locale + '"');
res.contentType('text/html; charset=UTF-8');
res.send(angularIndexFile.html());
});

module.exports = router;
  1. Now, when our Angular app loads, it will automatically inject the locale code from the incoming Accept-Language header into the index.html page. Angular will pick up this configuration and load the localization file for the locale.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.204.216