简体   繁体   English

无法通过 Express Js Router 请求和响应 Class 方法

[英]Cannot Passing Express Js Router Request and Respond to Class Method

I have a problem when creating express JS router.创建 express JS 路由器时遇到问题。

I can not passing req and res to my class method.我无法将 req 和 res 传递给我的 class 方法。

Not Work app.get('/', controller.index)不工作app.get('/', controller.index)

Work app.get('/', (res,req) => controller.index(req,res)工作app.get('/', (res,req) => controller.index(req,res)

The following is the flow of the routing that I made:下面是我做的路由的流程:
app.js (Main file) > /routes/index.js > /routes/user.route.js > /controllers/user.controller.js > /services/user.services.js app.js(主文件)> /routes/index.js > /routes/user.route.js > /controllers/user.controller.js > /services/user.services.js

app.js应用程序.js

import express from 'express';
import cors from 'cors';
import routes from './routes';
import db from './models';
import dotenv from 'dotenv';

dotenv.config();
const app = express();
const port = process.env.PORT || 3001;

app.use(cors())
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// Database Initialize
db.sequelize.sync()
.then(() => {
    console.log("🚀 Database Connected.");
}).catch((err) => {
    console.log("❌ Failed Connect to Database");
})

// Router
app.use(routes);

//global dir
global.__basedir = __dirname;

app.enable("trust proxy");

app.listen(port, () => {
  // logger.info("Checking the API status: Everything is OK");
  console.log(`🚀 App listening on port ${port}`);
})

routes/index.js路线/index.js

import express from "express";
import appRoutes from './app.routes';
import roleRoutes from './role.routes';
import userRoutes from './user.routes';
import authRoutes from './auth.routes';

const app = express();

// App Routes
app.use('/app', appRoutes);
// Role Routes
app.use('/role', roleRoutes);
// User Routes
app.use('/user', userRoutes);
// Auth Routes
app.use('/auth', authRoutes);

export default app;

routes/user.routes.js路线/user.routes.js

import express from 'express';
import userController from '../controllers/user.controller';
import validateAuth from '../middlewares/validateAuth';

const app = express();
const controller = new userController;

app.get('/', controller.index);

export default app;

controllers/user.controller.js控制器/user.controller.js

import userServices from "../services/user.services";
import baseController from "./base.controller";

export default class userController extends baseController {
    constructor() {
        super(new userServices());
    }
}

controllers/base.controller.js控制器/base.controller.js

import response from "../helpers/response";
import lang from "../helpers/lang";
import dotenv from "dotenv";
dotenv.config();

export default class baseController {
    constructor(service) {
        this.service = service
    }

    /**
     * Index
     * Get all data with pagination
     */
    async index(res, req) {
        try {
            const data = await this.service.paginate(req.query);
            if(data) {
                return response.success({
                    res,
                    message: lang[process.env.LANG].DATA_LOADED,
                    data
                });
            } else {
                throw new Error(lang[process.env.LANG].REQUEST_FAILED);
            }
        } catch(err) {
            console.log(err)
            return response.error({
                res,
                message: err.message,
            });
        }
    }
}

services/user.services.js服务/user.services.js

import baseServices from "./base.services";
import db from "../models";

export default class userServices extends baseServices {
    constructor() {
        const attributes = [
            "roleId",
            "appId",
            "username",
            "password",
            "name",
            "phone",
            "email",
            "isActive",
        ];
        super(db.user, attributes);
    }

    /**
     * Paginate
     * @param {{
     *  search: string,
     *  limit: number,
     *  offset: number,
     *  sortBy: string,
     *  orderBy: string,
     *  user: object
     * }} data
     * return Promise
     */
    paginate(data) {
        const { search, limit, page, sortBy, orderBy, user } = data;

        const offset = limit
            ? parseInt(limit) * parseInt(page) - parseInt(limit)
            : 0;

        let filter = {};
        if (search)
            Object.assign(filter, { name: { [Op.like]: `%${search}%` } });

        const condition = {
            where: filter ? filter : "",
            order: sortBy ? [[sortBy, orderBy]] : [["name", "asc"]],
            limit: limit ? parseInt(limit) : 10,
            offset,
            include: ["role", "app"]
        };

        return this.model.findAndCountAll(condition);
    }
}

services/base.services.js服务/base.services.js

import db from "../models";
const Op = db.Sequelize.Op;

/**
 * Base Services Class
 */
export default class baseServices {
    constructor(model, attributes = []) {
        this.model = model;
        this.attributes = attributes
    }
}

Response回复

Not Work app.get('/', controller.index)不工作app.get('/', controller.index)
Error Response错误响应

Work app.get('/', (res,req) => controller.index(req,res)工作app.get('/', (res,req) => controller.index(req,res)

Success Response成功响应

I was try to change const app = express() and const app = express.Router() but still have the same problem.我试图改变const app = express()const app = express.Router()但仍然有同样的问题。

I see two things wrong here:我在这里看到两件错误的事情:

  1. You are losing the controller object in the index method because of the way you're passing the index method.由于传递索引方法的方式,您在索引方法中丢失了controller object。

  2. You are doing some very confusing things with the order of the (req, res) arguments.你正在用(req, res) arguments 的顺序做一些非常混乱的事情。

Your controller.index() method declares them in reverse as:您的controller.index()方法将它们反向声明为:

async index(res, req) { ... }

So, that's why:所以这就是为什么:

app.get('/', controller.index)

doesn't work.不起作用。 Because the arguments are passed as (req, res) by Express, but your method expects them as (res, req) .因为 arguments 被 Express 作为(req, res)传递,但是您的方法期望它们作为(res, req)

Then, the reason that this works:然后,这是有效的原因:

app.get('/', (res,req) => controller.index(req,res));

is because you reverse the argument again.是因为你又颠倒了论点。


So, change the method to this:因此,将方法更改为:

async index(req, res) { ... }

so, it matches the way Express passes the arguments and then the arguments will be correct.因此,它匹配 Express 传递 arguments 的方式,然后 arguments 将是正确的。

Then, because your controller object has instance data and the index method uses this , you also need to make sure the index method is getting passed it's instance properly in this by changing to this:然后,因为你的controller object 有实例数据并且index方法使用this ,你还需要确保 index 方法通过更改为this正确地传递它的实例:

app.get('/', controller.index.bind(controller));

You should follow the correct MVC pattern and repeat after me, your app.js should be:你应该遵循正确的MVC模式并跟着我重复,你的app.js应该是:

require ('dotenv').config();
const routes =  require('./routes');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
const cors = require('cors');
const db = require('./models');

const port = process.env.PORT || 3001;

app.use(cors());
app.use(express.json());

// Database Initialize
db.sequelize.sync()
.then(() => {
    console.log("🚀 Database Connected.");
}).catch((err) => {
    console.log("❌ Failed Connect to Database");
})

// Router
app.use(routes);

//global dir
global.__basedir = __dirname;

app.enable("trust proxy");

app.listen(port, () => {
  // logger.info("Checking the API status: Everything is OK");
  console.log(`🚀 App listening on port ${port}`);
})

The routes/index.js file should follow the structure: routes/index.js文件应遵循以下结构:

const router = require("express").Router();

router.use('/app', require(./app.routes"));
router.use('/role', require("./role.routes"));
router.use('/user', require("./user.routes"));
router.use('/auth', require("./auth.routes"));


module.exports = router;

Your all routes file should be like this你所有的路线文件应该是这样的

user.routes用户.routes

const userController = require("whatever the location");
const router = require("express").Router();

router.post("/example", userController.controller);

module.exports = router;

The userController file:用户控制器文件:

const userServices = require("what ever the location");

const controller = async (request, response) => {
    try {
        //code goes here
        await userServices.addUser(
        {
                "name": "ALI",
                "gender": "MALE",
        }
    )
    } catch (error) {
        console.log(error);
        response.status(500).json({
            error: "Something went wrong",
        });
    }
}

module.exports = {
    controller
}

And finally the userServices file is:最后 userServices 文件是:

const user = require("what ever the location");

const addUser = async (data) => {

    return new Promise((resolve, reject) => {
        new user(data)
            .save()
            .then((data) => resolve(data))
            .catch((err) => reject(err));
    });

}

module.exports = {
    addUser
}

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

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