res.redirect在提交表单后显示旧信息? [英] res.redirect showing old information after form submission?

查看:84
本文介绍了res.redirect在提交表单后显示旧信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个node.js应用程序,其中创建了一个用户个人资料页面.我将其设置为可编辑,以便他们可以根据需要更新其名称.

I have a node.js app in which I created a user profile page. I made it editable so they can update their name if they want to.

但是,当我单击表单上的保存更改"按钮时,它会重定向到正确的页面,但显示旧信息.只有刷新页面或离开页面后,才会显示更新的信息.

However, when I click the 'Save Changes' button on the form, it redirects to the correct page but shows the old information. Only once you refresh the page or navigate away from it does the updated information show.

提交表格html:

<form action="./profile" method="POST">
<div class="form-group">
    <label for="">Full Name</label>
    <input type="text" class="form-control" value="<%= name %>" 
name="name"> 
</div>
<div class="form-group" >
    <label for="">email</label>
    <input type="text" class="form-control" value="<%= email %>" readonly>
</div>
<div class="form-row">
    <div class="form-group">
        <button type="submit" class="btn btn-info"><a href="profileEditor"> 
</a> Save Changes</button>
    </div>
    <p>&nbsp; &nbsp;</p>
    <div class="form-group">
        <button class="btn btn-dismiss"><a href="./profile">Exit</a> 
</button></a>
    </div>
</div>

</form>

index.js的一部分(在我的路由文件夹中)

parts of index.js (in my routes folder)

const express = require('express');
const router = express.Router();
const { ensureAuthenticated } = require('../config/auth');
const mongoose = require('mongoose');
const User = require('../models/User');

router.post('/', ensureAuthenticated, (req, res) => {
   updateRecord(req,res);
   res.redirect('/profile');
});

function updateRecord(req, res) {
User.findOne({_id:req.user.id},(err,doc)=>{
 //this will give you the document what you want to update.. then 
doc.name = req.body.name;
doc.save(function(err,doc){
}); 
});   
}

module.exports = router;

在我的router.post函数下,res.redirect可以工作并将用户发送到"/profile",但不显示更新的数据库信息.请帮忙!

under my router.post function, the res.redirect works and sends the user to '/profile' but doesn't show the updated database info. Please help!

推荐答案

您可以直接使用findOneAndUpdate()函数更新用户配置文件.尝试如下操作:

You can directly use findOneAndUpdate() function to update user profile. Try as below:

const express = require('express');
const router = express.Router();
const { ensureAuthenticated } = require('../config/auth');
const mongoose = require('mongoose');
const User = require('../models/User');

router.post('/', ensureAuthenticated, (req, res) => {
  User.findOneAndUpdate({_id:req.user.id},{name: req.body.name},{new: true},(err,doc)=>{
       console.log('#### Updated Record ####',doc);
       res.redirect('/profile');
  });   
});



module.exports = router;

这篇关于res.redirect在提交表单后显示旧信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆