如何应用程序使用来自不同文件的所有路由 [英] How to app use all routes from different file

查看:72
本文介绍了如何应用程序使用来自不同文件的所有路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试分隔路线,之前我将其包含到我的app.js中

I'm trying to separate my routes, previously i'm including them to my app.js

/backend/app.js

/backend/app.js

const express = require("express");
const router = require("./routes");
const status = require("./routes/status");
const register = require("./routes/register");
const login = require("./routes/login");


app.use('/', router);
app.use('/status', status);
app.use('/login', login);
app.use('/register', register);

我意识到它是不理想的,因为我稍后会添加越来越多的路由,而app.js将被它们污染

I realized its not ideal since i am adding more and more routes later on and the app.js will be polluted with them

我现在要做的只是将index.js导入到app.js中,基本上该索引具有所需的所有路由

What i want to do now is just to import an index.js to app.js and basically this index have all the routes needed

/后端/路由/索引

const routes = require("express").Router();
const root = require("./root");
const status = require("./status");
const register = require("./account/register");
const login = require("./account/login");


routes.use("/",  root);
routes.use("/login", login);
routes.use("/register", register);
routes.use("/status", status);
and now in the app.js i can just include the index

const routes = require("./routes");
app.use('/', routes);

但在尝试请求登录路由时无法正常工作,并收到404错误

but its not working im getting 404 error when trying to request to login route

im像这样导出它们

module.exports = routes;

推荐答案

在您的app.js中

app.use('/', require('./backend/routes/index'))

然后,在您的路线/索引中

Then, in your routes/index

import express from 'express'

const router = express.Router()

// GET /
router.get('/', function (req, res) {

})

// GET /countries
router.get('/countries', (req, res, next) => {

})

// POST /subscribe
router.post('/subscribe', checkAuth, generalBodyValidation, (req, res, next) => {

})

// All routes to /admin are being solved in the backend/routes/admin/index file
router.use('/admin', require('./backend/routes/admin/index'))

module.exports = router

您的管理员/索引文件可以是 从"express"导入快递

Your admin/index file can be import express from 'express'

const router = express.Router()

// POST /admin/login
router.post('/login', (req, res, next) => {

})

module.exports = router

通过此操作,您将能够向/admin/login执行POST请求.

With this, you will be able to perform a POST request to /admin/login.

希望这可以解决您的问题,如果它确实将我的答案标记为正确,如果不告诉我出了什么问题,我会解决它:D

Hope this solves your problem, if it does mark my answer as correct, if not tell me what went wrong and I will solve it :D

这篇关于如何应用程序使用来自不同文件的所有路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆