Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SOLVED: Pass data through middleware or router in Express

Maquessime Chevallier:

I am developping a web service and I the server to manage the content negociation in term of language (Accept-Language). I don't know really how we do in Express. But I have done some code :


router.all('/*', (req, res, next) => {
var enFrancais = true
var languagesAsked = req.headers["accept-language"]
languagesAsked = languagesAsked.split(',')
var languages = []
for (var languagesAsked of languagesAsked) {
try {
languages.push({language: languagesAsked.split(";")[0],
pref: languagesAsked.split(";")[1].split("=")[1]})
} catch(err) {
languages.push({ language: languagesAsked, pref: "1"})
}
}
_.sortBy(languages, "pref")
if(!languages[0].language.startsWith('fr')) {
enFrancais = false
}
next() //next(enFrancais) don't works. => ERR 500
});

router.get('/', (req, res, next) => {
var APIconfiguration = {
version: "0.1",
baseUrl: "/api",
date: new Date(),
responseLanguage: enFrancais
}
res.send(APIconfiguration)
});

The first router return true if the Accept-Language header of the HTTP header says "I prefer French" or falseif not.

I want in each call of the service that this router (or middleware if it has to be one) manage this HTTP header (to not write this code twice.)

Can I pass the data from the first part to the second part properly ?

Thanks for reading.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE


This post first appeared on Stack Solved, please read the originial post: here

Share the post

SOLVED: Pass data through middleware or router in Express

×

Subscribe to Stack Solved

Get updates delivered right to your inbox!

Thank you for your subscription

×