[英]Nodejs how can I add another main app.js and use both of them to make my code clean?
这是您的项目的简化结构,该结构源自此链接上的我的项目。
路线.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)
希望能帮助到你:)
根据您的设置,您可以按示例划分文件:
然后将 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.