HapiJS全局路径前缀 [英] HapiJS global path prefix

查看:125
本文介绍了HapiJS全局路径前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在HapiJS上编写API,并想知道如何获取全局前缀.例如,所有请求都应发送至:

I'm writing an API on HapiJS, and wondering how to get a global prefix. For example, all requests should be made to:

https://api.mysite.com/v0/...

所以我想将v0配置为全局前缀.文档(此处)似乎没有提到它-在HapiJS中有什么好方法吗?

So I'd like to configure v0 as a global prefix. The docs (here) don't seem to mention it -- is there a good way to do this in HapiJS?

推荐答案

如果将API路由逻辑放在 Hapi中插件,说./api.js:

If you put your API routing logic inside a Hapi plugin, say ./api.js:

exports.register = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/hello',
        handler: function (request, reply) {
            reply('World');
        }
    });

    next();

};

exports.register.attributes = {
    name: 'api',
    version: '0.0.0'
};

您在服务器上注册了插件,并传递了可选的路由前缀,该前缀将添加到插件内部的所有路由之前:

You register the plugin with a server and pass an optional route prefix, which will be prepended to all your routes inside the plugin:

var Hapi = require('hapi');

var server = new Hapi.Server()
server.connection({
    port: 3000
});

server.register({
    register: require('./api.js')
}, {
    routes: {
        prefix: '/v0'
    }
},
function(err) {

    if (err) {
        throw err;
    }

    server.start(function() {
        console.log('Server running on', server.info.uri)
    })

});

您可以通过启动服务器并访问http://localhost:3000/v0/hello来验证此工作.

You can verify this works by starting the server and visiting http://localhost:3000/v0/hello.

这篇关于HapiJS全局路径前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆