[英]How to move data of request body from one route to another in Express
On my MERN application, I have two routes.在我的 MERN 应用程序中,我有两条路线。 One for 'Storing Data', let's call it 'data' route and another to 'Register User', so call it 'register' route.
一个用于“存储数据”,我们将其称为“数据”路由,另一个用于“注册用户”,因此将其称为“注册”路由。
When sending a request to 'data' route, the client might send 'username, password & name', because that is optional.当向“数据”路由发送请求时,客户端可能会发送“用户名、密码和名称”,因为这是可选的。
Now, if the client does send 'username, password & name'.现在,如果客户端确实发送了“用户名、密码和名称”。 how can I redirect those data from 'data' route to 'register' route, and then return a response back to the 'data' route and then store the data to database?
如何将这些数据从“数据”路由重定向到“注册”路由,然后将响应返回到“数据”路由,然后将数据存储到数据库?
Individually, both the routes are working.就个人而言,两条路线都在工作。 I just don't know how to transfer certain data to one route to another.
我只是不知道如何将某些数据传输到另一条路线。
This is Data route file:这是数据路由文件:
router.post('/', async (req, res) => {
const { data, email, password, name } = req.body;
if(email && password && name) {
// Register User here
}
// code to store data to database will go here
});
module.exports = router;
This is Register Route file:这是注册路由文件:
router.post('/', async (req, res) => {
const { email, password, name } = req.body;
try {
let user = await User.findOne({ email });
if (user) {
return res.status(400).json({ msg: 'User already exists' });
}
user = new User({
name,
email,
password,
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
} catch (err) {
console.error(err.message);
res.status(500).json('Server Error');
}
});
module.exports = router;
You can chain your controllers together, just like you would do with middleware.您可以将控制器链接在一起,就像使用中间件一样。 Each controller is called with 3 arguments: request response and next;
每个 controller 用 3 个 arguments 调用:请求响应和下一步; calling next invokes next controller in chain.
调用 next 调用链中的下一个 controller。 Note that setting response ( eg
res.send()
) AND calling next will result in error, so only set response once.请注意,设置响应(例如
res.send()
)并调用 next 将导致错误,因此只需设置一次响应。
router
.route('/')
.post(
function register(req, res, next){
if(!/* my completeness check */){
return next()
} else {
res.send('done!')
}
},
function store(req, res){
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.