简体   繁体   中英

`Cannot GET /apiv1/accounts` - Nested routes don't work in Express.js

I am writing a backend API in Express with the help of @awaitjs/express .

I am having troubles with hitting the 'double nested' endpoints.

eg

// 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);

Going to /apiv1 works, and produces the expected output.

When I am trying to do this

// 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 };

and then go to /apiv1/accounts/foobar , it tells me <pre>Cannot GET /apiv1/accounts</pre> and I get a 404 error [...] "GET /apiv1/accounts HTTP/1.1" 404 153

Any ideas?

Just as a side note, this is what I have above my /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);
});

Yes, I have looked for other solutions prior to posting, yet I did not see anything particularly helpful.

UPDATE 1 When I do

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

Everything works beautifully. So it's mongoose ?

Ok I figured out what caused the weird problem.

Turns out, that making the app synchronous (ie removing everything connected to @awaitjs/express ) fixed everything.

Whilst it is not an optimal solution for sure, it does solve the core problem of my app not working.

You sure about the API url?

It usually is /api/v1 not /apiv1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM