【发布时间】: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