【问题标题】:`Cannot GET /apiv1/accounts` - Nested routes don't work in Express.js`Cannot GET /apiv1/accounts` - 嵌套路由在 Express.js 中不起作用
【发布时间】:2021-01-16 23:58:20
【问题描述】:

@awaitjs/express 的帮助下,我正在Express 中编写一个后端API。

我在点击“双嵌套”端点时遇到了麻烦。

例如

// in src/routes/routes.ts being an api router file
// apiv1router is exported from here

app.getAsync('/', (req, res, next) => {
    res.send("I work");
})
-------
// in src/server.ts being an entry file
app.useAsync('/apiv1', apiv1router);

转到/apiv1 工作,并产生预期的输出。

当我尝试这样做时

// src/routes/routes.ts
import { Router } from '@awaitjs/express';
import { router as accountsRouter } from './AccountRoutes/AccountRoutes';

const router = Router();

router.useAsync('/', accountsRouter);

------

// src/routes/AccountRoutes/AccountRoutes.ts
import { Request, Response, NextFunction } from 'express';
import { Router } from '@awaitjs/express';

router.getAsync(
    '/accounts/:accountType',
    async (request: Request, response: Response, next: NextFunction) => {
        try {
            requestValidator(request, next, response);
            const accountsList = await accountModel.find({
                accountType: request.params.accountType,
            });
            response.status(200).json(accountsList);
        } catch (error) {
            return error;
        }
    }
);
export { router as accountsRouter };

然后转到/apiv1/accounts/foobar,它告诉我<pre>Cannot GET /apiv1/accounts</pre>,我收到一个404错误[...] "GET /apiv1/accounts HTTP/1.1" 404 153

有什么想法吗?

顺便说一句,这就是我上面的/apiv1

import express, { Request, Response, Errback, NextFunction } from 'express';
import { addAsync } from '@awaitjs/express';

import helmet from 'helmet';
import cors from 'cors';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import mongoose from 'mongoose';

const PORT = process.env.PORT;

import { router as apiv1router } from './routes/routes';

const app = addAsync(express());

const mongoURI =
    process.env.MONGOURI;

app.useAsync(express.json());

app.useAsync(helmet());
app.useAsync(cors());


app.useAsync(bodyParser.urlencoded({ extended: true }));

app.useAsync(morgan('common'));

// Without that simple error handling middleware it did not work anyway
app.useAsync((err: any, req: Request, res: Response, next: NextFunction) => {
    console.error(err.stack);
});

是的,我在发布之前已经寻找其他解决方案,但没有发现任何特别有用的解决方案。

更新 1 当我这样做时

router.getAsync(
    '/accounts/:accountType',
    async (request: Request, response: Response, next: NextFunction) => {
      response.json(request.params.accountType)
    }
);

一切都很完美。所以是mongoose

【问题讨论】:

    标签: javascript typescript express asynchronous routes


    【解决方案1】:

    好的,我知道是什么导致了这个奇怪的问题。

    事实证明,使应用程序同步(即删除连接到@awaitjs/express 的所有内容)修复了所有问题。

    虽然它肯定不是最佳解决方案,但它确实解决了我的应用无法运行的核心问题。

    【讨论】:

    • 这对短期使用有好处,但从长远来看,同步执行所有操作可能(极大地)影响应用速度和用户体验。您将不得不对此进行更多研究并找到使用异步的方法。
    • 很遗憾,这是真的。我希望对于 MVP 来说应该没问题,然后假设最多有 1000 个用户。我猜是“鸭带”编程。
    【解决方案2】:

    您确定 API 网址?

    通常是/api/v1 而不是/apiv1

    【讨论】:

    • 相当肯定。我想我可以将其更改为 /api/v1 但这不是这里的问题
    猜你喜欢
    • 2016-07-28
    • 2015-11-25
    • 1970-01-01
    • 2016-11-23
    • 2017-10-04
    • 2017-04-17
    • 2014-10-05
    • 2016-02-07
    • 1970-01-01
    相关资源
    最近更新 更多