【问题标题】:Sequelize ExpressJS Using Id for Post Method使用 ID 为 Post 方法续集 ExpressJS
【发布时间】:2015-12-29 02:25:29
【问题描述】:

我有一个用于编辑和更新特定 ID 记录的表单,我可以在我的 GET 方法中使用 req.params.annotationId 访问我的路由的 ID,但是当我尝试使用 POST 时使用req.body.annotationId 获取参数的版本我得到了NULL 返回的值。我还尝试使用req.params.annotationId,它返回了路由的:annotationId 占位符。这是因为表单中不存在该字段吗?这会有意义,因为 body-parser 会查找字段中存在的值?

这是来自 POST 方法的查询结果:

Executing (default): SELECT `annotation_id` AS `annotationId`, `annotation_date` AS `annotationDate`,`user_id` AS `userId`, `createdAt`, `updatedAt`, `userUserId` FROM `annotation` AS `annotation` WHERE `annotation`.`user_id` = 1 AND `annotation`.`annotation_id` = NULL LIMIT 1;

这是我的路线:

appRoutes.route('/edit/:annotationId')

    .get(function(req, res){
        console.log('This is the url path ' + req.originalUrl);

        console.log(req.params.annotationId);

        models.Annotation.find({
                where: {
                    userId: req.user.user_id,
                    annotationId: req.params.annotationId
                },attributes: ['annotationId', 'annotationDate']
            }).then(function(annotation){
                res.render('pages/annotation-edit.hbs',{
                    annotation: annotation,
                    user: req.user,
                    editMode: req.originalUrl
                });
        })          
    })


    .post(function(req, res){

        console.log("POST method triggered");

        console.log(req.params.annotationId);

        models.Annotation.find({
            where: {
                    userId: req.user.user_id,
                    annotationId: req.body.annotationId
            }
        }).then(function(annotation){
                if (annotation) {
                    console.log("Annotation exists");
                    annotation.update({
                        annotationDate: req.body.annotationDate,
                        userId: req.user.user_id
                    }).success(function() {
                        console.log("Annotation Updated");
                    });
                }
            })
        });

这是我的注释模型:

  module.exports = function(sequelize, DataTypes) {

    var Annotation = sequelize.define('annotation', {
        annotationId: {
            type: DataTypes.INTEGER,
            field: 'annotation_id',
            autoIncrement: true,
            primaryKey: true
        },
        annotationDate: {
            type: DataTypes.DATE,
            field: 'annotation_date'
        },
        userId: {
            type: DataTypes.STRING,
            field: 'user_id'
        }
    },

     {
        freezeTableName: true,
        },
        classMethods: {
            associate: function(db) {
                Annotation.belongsTo(db.User)
            }
        }
    });
        return Annotation;
    }

这是 POST 请求的格式:

<div class="row">
    <div class="col-md-8 col-md-offset-2">
        <div class="annotation-form">
            <form action="/app/edit/:annotationId" method="post">
                <div class="annotation-form-header">
                    <img class="user-image" src="http://placehold.it/80x80" alt="Generic placeholder image">
                    <label for="annotation-date">Annotation Date:</label>
                    <input type="date" name="annotationDate" id="annotation-form-date" value="{{annotation.annotationDate}}">
                </div>
                <button type="submit" id="create-annotation-button">Update Annotation</button>
            </form>

【问题讨论】:

    标签: node.js express sequelize.js


    【解决方案1】:

    req.body.annotationId 从数据中获取 annotationID,格式如下:

    <form action="/app/edit" method="post">
                    <input name="annotationId" type="hidden" value="121313">
                    <div class="annotation-form-header">
                        <img class="user-image" src="http://placehold.it/80x80" alt="Generic placeholder image">
                        <label for="annotation-date">Annotation Date:</label>
                        <input type="date" name="annotationDate" id="annotation-form-date" value="{{annotation.annotationDate}}">
                    </div>
                    <button type="submit" id="create-annotation-button">Update Annotation</button>
                </form>
    

    ```

    req.params.annotationId 从 URL 获取 annotationID:/edit/4465465

    &lt;form action="/app/edit/:annotationId" method="post"&gt;

    【讨论】:

    • 感谢您的回答。隐藏字段似乎修复了使用正确的 ID 值进行的 SQL 查询,但我在提交表单时遇到了无限循环。我使用/app/edit/:annotationId 的原因是因为它是我为bot 路由get 和post 方法。我拆分了让帖子来自/app/edit 的路线,并且发生了同样的无限循环。知道为什么会这样吗?
    • 你需要对 Post 方法的响应,如果错误应该添加 catch 逻辑
    • 我添加了}).catch(function(error){ res.send(error); }),但没有触发错误。我确实注意到我的 `console.log("Annotation exists"); ` console.log 没有被触发。这是否表明问题存在于我的.update 方法之前?
    • 我发现了问题,我需要.update 而不是.find,然后将where 子句放在更新方法中
    【解决方案2】:

    表单应该使用handlebars对象来传递当前选择的Id,像这样,

    <form action="/app/edit/{{annotation.annotationId}}" method="post">
                    <input name="annotationId" type="hidden" value="121313">
                    <div class="annotation-form-header">
                        <img class="user-image" src="http://placehold.it/80x80" alt="Generic placeholder image">
                        <label for="annotation-date">Annotation Date:</label>
                        <input type="date" name="annotationDate" id="annotation-form-date" value="{{annotation.annotationDate}}">
                    </div>
                    <button type="submit" id="create-annotation-button">Update Annotation</button>
                </form>
    

    然后应该将路由从.find 更改为.update

    .post(function(req, res){
    
            console.log("POST method triggered");
    
            console.log(req.params.annotationId);
    
            models.Annotation.update({
                annotationId: req.body.annotationId,
                annotationDate: req.body.annotationDate,
            },{where:{
                userId: req.user.user_id,
                annotationId: req.body.annotationId
            }}).then(function(){
                console.log("Annotation was Updated");
                res.redirect('/app');
            });
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多