Javascript 使用node.js和sequelize将表单数据插入到mysql数据库表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26798862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:23:40  来源:igfitidea点击:

Insert form data into mysql database table using node.js and sequelize

javascriptmysqlnode.js

提问by ST80

I have a NodeJSapp and I want to insert some data from a form into a table of my MySQL-database by using the sequelize()-method.

我有一个NodeJS应用程序,我想MySQL使用sequelize()-method 将表单中的一些数据插入到我的-database的表中。

So here is my form

所以这是我的表格

<form id="addVideo" method="post">
    <input type="url" name="video_url" required></input>
    <input type="hidden" value="" name="artist_id"></input>
    <input type="hidden" value="youtube" name="type"></input>
</form>

My post function:

我的帖子功能:

$('form#addVideo').submit(function(e){
    e.preventDefault();

    var form = $(this);
    var jsonvideoFormData = utils.serializeToJSON(form);
    var xhrData = _.pick(jsonvideoFormData, 'video_url', 'artist_id', 'type');

    api.post('/videos', xhrData, function(response){
       alert('Video has been added!');
    });
});

Then the backend code looks like this:

然后后端代码如下所示:

exports.addVideo = function(req, res, next){

  var videoURL = req.body.video_url;
  var artistId = req.body.artist_id;
  var type = req.body.type;

  db.sequelize.query('INSERT INTO social_urls (artist_id,urls,type) VALUES('artistId','videoURL','type')', function(err) {
    if(err){
        return res.json(400, {response: {code: 400, message:'An error appeared.'}});
    } else{
       console.log('succes');
       res.json(201, {response: {code: 201, message: 'Video has been added'}});
    }   

  });

}

But for some reason I do not know this is not working. Can anyone help me out?

但出于某种原因,我不知道这是行不通的。谁能帮我吗?

Many thanks!!

非常感谢!!

回答by laruiss

I am not an expert in sequelize, but I see there code prone to SQL Injection.

我不是 sequelize 方面的专家,但我看到那里的代码容易发生 SQL 注入。

This is wrong:

这是错误的:

db.sequelize.query('INSERT INTO social_urls (artist_id,urls,type) VALUES('artistId','videoURL','type')', function(err)

It should be, at least:

至少应该是:

db.sequelize.query("INSERT INTO social_urls (artist_id,urls,type) VALUES('" + artistId + "','" + videoURL + "','" + type + "')'", function(err)

But really, I think you should be doing something like this:

但实际上,我认为你应该做这样的事情:

var SocialUrl = sequelize.define('SocialUrl', {
  videoURL: Sequelize.STRING,
  artistId: Sequelize.STRING,
  type:     Sequelize.STRING
}, {
  tableName: 'social_urls',
  timestamps: false
});

SocialUrl
  .create({
    videoURL: videoURL,
    artistId: artistId,
    type: type
  })
  .complete(function(err, socialUrl) {
    if (err) {
      // log error;
    } else {
      // Do stuff
    }
  })

回答by Matthew

this is the actual query to save the data. Steps 2 & 3.

这是保存数据的实际查询。步骤 2 和 3。

  var videoURL = req.body.video_url;
  var artistId = req.body.artist_id;
  var type = req.body.type;

    models.socialUrls.build({ 
            artist_id: artistId, 
            urls: videoURL, 
            type: type
        })
          .save()
          .then(anotherTask => {
            console.log('the data saved!');
            // you can now access the currently saved task with the variable anotherTask... nice!
          })
          .catch(error => {
            console.log('uh oh something wasn't right!');
            console.log(error);
            // Ooops, do some error-handling
          })

If you check out the sequelize docs here: http://docs.sequelizejs.com/manual/tutorial/instances.html

如果您在此处查看续集文档:http://docs.sequelizejs.com/manual/tutorial/instances.html

There are 3 steps to saving the data.

保存数据有 3 个步骤。

  1. Creating the model
  2. Creating the instance, a.k.a data object within your callback. This is what gets sent to sequelize method to send to db.
  3. Calling the .save() method.
  1. 创建模型
  2. 在回调中创建实例,也就是数据对象。这是发送到 sequelize 方法以发送到数据库的内容。
  3. 调用 .save() 方法。

After that you can handle the errors with .catch()

之后,您可以使用 .catch() 处理错误

From what it looks like your problem is in your backend code. Make sure your model is correct and the data from your form is getting sent. Once you are sure of that you only need to do steps 2 and 3.

从看起来您的问题出在后端代码中。确保您的模型正确并且表单中的数据正在发送。一旦确定,您只需要执行步骤 2 和 3。

回答by Muthukumar

You don't have to JSON serialize data. You can just post the data.

您不必对数据进行 JSON 序列化。你可以只发布数据。

<form id="addVideo" method="post" action="/videos">
    <input type="url" name="video_url" required></input>
    <input type="hidden" value="" name="artist_id"></input>
    <input type="hidden" value="youtube" name="type"></input>
</form>

Remeber to use body-parser

记得使用 body-parser

app.use(require("body-parser")());

Now req.body.video_url should have the expected data.

现在 req.body.video_url 应该有预期的数据。