I'm currently updating a small library that I've made for parsing the locale from a request object. It's currently works with Express and Koa but I'm trying to get it to work with Hapi.
For tests, I'm using Mocha and Hapi's inject
method as described in their docs. I've also looked in their docs for setting the server's properties, but I do not find an example of setting a domain such as locahost.en
or even subdomains such as en.localhost.com
.
Currently, I have my test setup like the following:
var server = new Hapi.Server();
server.connection({
//is this correct?
uri:'localhost.en:3000',
port: 3000
});
var handler = function(request, reply) {
//return the parsed locale {String}
return reply(accept(request, {
supported: ['en']
}).getFromDomain());
};
server.route({
method: 'GET',
path: '/',
handler: handler
});
server.start(function() {});
where inject
is set like this:
server.inject({
method: 'GET',
url: '/',
headers: {
'Accept-Language': 'ja',
'Set-Cookie': 'mycookie=test'
}}, function(res) {
assert.strictEqual(res.result, 'en');
done();
});
How would I be able to set the domain and subdomain in the server properties? Is there a plugin that does that? Also, how could I get/parse the domain and subdomains from request
? I'm assuming I could get the domain from hostname
but how about the subdomain?
By default, Hapi will listen on a port on a network interface to all requests regardless of the domain (indicated by the value of the host
header). If you want to get the value of the host header for a request, you can simply check request.headers.host
.
If you just want to check the parsed hostname (domain), you can check request.info.hostname
server.route({
method: 'GET',
path: '/',
handler: function(request, reply) {
var hostname = request.info.hostname;
reply('Ok');
}
});
If you want to restrict the hostnames allowed for a route (or a plugin), you can set the vhost
option.
server.route({
method: 'GET',
path: '/',
vhost: ['en.example.com'],
handler: function(request, reply) {
reply('Ok');
}
});
To test different vhosts with server.inject
, you can just include an explicit host header
server.inject({
method: 'GET',
url: '/',
headers: {
'Set-Cookie': 'mycookie=test',
}}, function(res) {
Assert(res.statusCode === 404); // 404 because not en.example.com
});
server.inject({
method: 'GET',
url: '/',
headers: {
'Set-Cookie': 'mycookie=test',
'Host': 'en.example.com'
}}, function(res) {
Assert(res.statusCode === 200); // 200 because en.example.com
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With