node.js - 当我将 HTTP 方法设置为 * 时,为什么 Hapi 不匹配此路径

标签 node.js hapi.js

我的目标是创建一条路由,将请求代理到远程 API 的特定路径。我无法使该路由匹配 GET 请求。 POST 请求被匹配并且调用被传递。例如,从浏览器到/api/document 的 POST 请求成功代理到目标。不过,Hapi 使用 404 响应 GET/api/document。我可以使用不同的方法键值创建两条相同的路由,但这看起来并不干燥。

    server.route({
    path: '/api/{path*}',
    method: '*',
    config: {
        handler: {
            proxy: {
                passThrough: true,
                mapUri: function (request, callback) {
                    var baseUri = 'https://remote/services/v1';
                    var resourceUri = request.path.replace('/api', '');
                    var destinationUri = baseUri + resourceUri;

                    server.log('Proxying to: ' + destinationUri);
                    callback(null, destinationUri);   
                }
            }
        }
    }
});

    server.route({
        method: 'GET',
        path: '/{path*}',
        handler: {
            file: '../build/index.html'
        }
    });

最佳答案

根据docs ,当您在路由中的方法中使用“”通配符时,只有在未找到完全匹配的情况下才会匹配。您的“catchall”路由的方法与路由匹配,并且该方法更具体,因此它似乎是通过/{path} 路由。

method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually.

您可以通过使用通配符来捕获所有内容或传递代理路由的数组而不是使用通配符来解决此问题。

关于node.js - 当我将 HTTP 方法设置为 * 时,为什么 Hapi 不匹配此路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25878122/

相关文章:

javascript - passport.js 中的 Date.now 无法完成

node.js - 带有 Passport 的 nodejs/hapi 应用程序中的模块化

node.js - postman 上的 POST 请求未完成

node.js - Hapijs - 服务器重新启动时 HttpOnly cookie 消失

node.js - 不使用hapi在nodejs中加载jquery文件

javascript - 在表中保存空字符串

node.js - semantic-release 配置为仅从 master 发布

javascript - Cookie 未在 node.js 中设置

node.js - 当存在index.d.ts时,TypeScript不会导入index.js

node.js - 从 hapi 路由中的异步函数返回