Javascript `无法获取/apiv1/accounts`-嵌套路由不';我不能在Express.js中工作
在Javascript `无法获取/apiv1/accounts`-嵌套路由不';我不能在Express.js中工作,javascript,typescript,express,asynchronous,routes,Javascript,Typescript,Express,Asynchronous,Routes,在@awaitjs/Express的帮助下,我正在Express中编写一个后端API 我在命中“双嵌套”端点时遇到问题 e、 g 转到/apiv1工作,并产生预期的输出 当我试图这样做的时候 // src/routes/routes.ts import { Router } from '@awaitjs/express'; import { router as accountsRouter } from './AccountRoutes/AccountRoutes'; const router
@awaitjs/Express
的帮助下,我正在Express
中编写一个后端API
我在命中“双嵌套”端点时遇到问题
e、 g
转到/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
,它告诉我
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
当我这样做的时候
一切都很好。所以是猫鼬
?你确定API url吗
通常是
/api/v1
而不是/apiv1
好吧,我找到了引起这个奇怪问题的原因
router.getAsync(
'/accounts/:accountType',
async (request: Request, response: Response, next: NextFunction) => {
response.json(request.params.accountType)
}
);
事实证明,使应用程序同步(即删除所有连接到@awaitjs/express
)可以修复所有问题
虽然这肯定不是一个最佳解决方案,但它确实解决了我的应用程序无法运行的核心问题。非常确定。我想我可以把它改成
/api/v1
,这不是这里的问题,这对短期使用是有好处的,但从长远来看,同步做任何事情都可能(显著)影响应用程序的速度和用户体验。您必须对此进行更多的研究,并找到使用异步的方法。遗憾的是,这是真的。我希望,这对MVP来说应该没问题,然后对1000名用户来说也没问题我猜是鸭式磁带编程。
router.getAsync(
'/accounts/:accountType',
async (request: Request, response: Response, next: NextFunction) => {
response.json(request.params.accountType)
}
);