首页 > 解决方案 > Nodejs:如何将请求数据从一个模块重用到另一个模块?

问题描述

我需要做的: 我想从 user.js 中获取用户选择的 First_Name 到 identity.js 文件中,以将其存储在另一个 MySQL 表中。使用它后将变为/清空以防止内存泄漏也很好。感谢您的帮助。

我有的:

********server/app.js*********
const express = require('express');
const app = express();
const addUser = require('./routes/user');
const identity = require('./routes/identity');
const port = 8080;
const cors = require('cors');
app.use(cors());

// routes for the app
app.post('/add', addUser);
app.use('/identity', identity);

// set the app to listen on the port
app.listen(port, () => {
    console.log(`Server running on port: ${port}`);
});


*******user.js******
module.exports = {
    addUser: (req, res) => {

        let First_Name = req.body.First_Name;
        let Last_Name = req.body.Last_Name;

        let query = "INSERT INTO `user` (First_Name, Last_Name) VALUES ('" +
                    First_Name + "', '" + Last_Name + "')";
        db.query(query, (err, result) => {
          if (err) {
              return res.status(500).send(err);
              }
           res.send('Success');
           console.log('User Created successfully !');
        });            
    }
};

******identity.js*********
const identity = express.Router();

//Store the selected option from Radiobutton in MySQL into another table
identity.post('/', (req, res) => {

    let selection = req.body.selectedOption;
    //***here I want to get First_Name which user selected in user.js***
    //const query = "INSERT INTO `document` (First_Name , selection ) VALUES ('" + First_Name + "','" + selection + "')";
    db.query(query, (err, _result) => {
        if (err) {
            return res.status(500).send(err);
        }
        res.send('Success');
        console.log('stored successfully !');
    });
});
module.exports = identity;

标签: node.jsreactjsexpressreact-routernode-modules

解决方案


将您的数据库帖子提取到它自己的函数中并给它一个接口(query) => Promise。目前,您正在写入数据库并在一个地方回复。

使新的数据库函数返回一个 Promise,它将根据发布到数据库的结果来解决或拒绝。

然后在 post 处理程序中,调用该函数并根据 Promise 结果响应 Web 请求。

导出数据库功能。从用户模块导入它,并在那里使用它。

让你的函数只做一件事,并为它们提供暴露它的接口。您的数据库帖子将查询发布并返回有关结果的语句。

您的处理程序接受请求,调用执行操作的函数,并根据结果做出响应。一旦您将该 db 函数移出,两个处理程序都将具有该形状。

它是控制器/服务的关注点分离。


推荐阅读