繁体   English   中英

Nodejs 如何添加另一个主 app.js 并使用它们来使我的代码干净?

[英]Nodejs how can I add another main app.js and use both of them to make my code clean?

您好,我正在使用 nodejs 和 express 框架,并且我将所有服务器端代码都写入了我的 app.js 文件,但这对我来说有点复杂,因为我有将近 250 行代码,我现在想实现身份验证,所以我想创建另一个app.js 只为身份验证编写我的代码,所以其他代码不会让我感到困惑我该怎么做????

更新在此处输入图像描述

正如您在上面看到的那样,我有 2 个来自我的 app.js 的发布请求我想在我的 auth.js 文件中

这是您的项目的简化结构,该结构源自链接上的我的项目。

路线.js

创建一个名为 route.js 的文件,在其中定义应用程序的所有路由。 在这种情况下,路由将只是由 UserController 模块处理的注册和登录路由。

import { Router } from 'express';
import UserController from './UserController';

const router = Router();

router.post(
  '/register',
  UserController.register
);
router.post(
  '/login',
  UserController.login
);

export default router;

用户控制器.js

这个文件/类处理创建和登录用户的所有操作

如您所见,所有方法都没有路由 url 因为它们是直接从我们的 route.js 文件中调用的。 我们正在划分和构建您的应用程序!

export default class UserController {
  public static register(req, res) {
    // Register operation
  }

  public static login(req, res) {
    // Login operation
  }
}

应用程序.js

入口点以及配置快速应用程序的位置。

import express from 'express';
import routes from './routes';

const app = express();

// configure app ...

// Here we attach our routes url to the express app
app.use('/', routes)

希望能帮助到你:)

根据您的设置,您可以按示例划分文件:

  • 应用程序.js
  • 身份验证.js

然后将 authentication.js 文件中的函数 require 或导入到 app.js 中,如下所示:

import express from "express";

或这个:

const express = require("express");

身份验证文件中的函数应该像这样导出:

//needs to be imported as this: import {authenticate} from "authenticate";
export function authenticate(){}; 

//needs to be imported as this: import authenticate from "authenticate";
function authenticate(){};
export default authenticate;

或这个:

// needs to be imported as this: const authenticate = require("authenticate");
module.exports = function authenticate(){};

请参阅本指南以启用 ES6 导入,如上所示。 这有偏好,因为它可以在导入时节省 memory。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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