node.js - 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;
解决方案
将您的数据库帖子提取到它自己的函数中并给它一个接口(query) => Promise
。目前,您正在写入数据库并在一个地方回复。
使新的数据库函数返回一个 Promise,它将根据发布到数据库的结果来解决或拒绝。
然后在 post 处理程序中,调用该函数并根据 Promise 结果响应 Web 请求。
导出数据库功能。从用户模块导入它,并在那里使用它。
让你的函数只做一件事,并为它们提供暴露它的接口。您的数据库帖子将查询发布并返回有关结果的语句。
您的处理程序接受请求,调用执行操作的函数,并根据结果做出响应。一旦您将该 db 函数移出,两个处理程序都将具有该形状。
它是控制器/服务的关注点分离。
推荐阅读
- python-3.x - 我正在尝试编写一个添加函数,为列表中的每个元素添加一个整数
- haskell - 更改 Haskell 中的属性
- r - R Markdown 中的西班牙字符在标题中起作用,但在正文中不起作用,即使它确实在纯乳胶中起作用
- java - List 中具有频率计数的唯一值
- >
- javascript - 来自 REST api 的 HTML 文件浏览器
- javascript - 我的按钮样式不想要,我似乎找不到如何更改它
- cakephp - CakePHP 3.7.1 DispatchShell 不执行迁移 Shell
- r - R - 如何用不同比例的两个 y 轴绘制 ggplot2 * 与时间变量
- django - 在 Django 中下载文件时如何在网页中显示某些内容
- android - Android ViewPager 不显示任何视图