使用sequelize POST方法在nodejs中插入新记录
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用sequelize POST方法在nodejs中插入新记录相关的知识,希望对你有一定的参考价值。
我想使用sequelize express在数据库中插入新数据,无需查询。我正在努力但我没有得到输出...如果我的代码是错误的,那么给我一个代码,用于使用sequelize express在db中插入新记录。
const Sequelize = require('sequelize');
var express = require('express');
var app = express();
var mysql = require('mysql');
//var request=require('request')
const sequelize = new Sequelize('ganeshdb', 'root', 'welcome123$', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
var users = sequelize.define('users', {
id: {
primaryKey: true,
type: Sequelize.INTEGER,
},
name: Sequelize.STRING,
role: Sequelize.STRING,
email: Sequelize.STRING
});
app.post('/test', function (request, response) {
return users.create({
name: request.body.name,
role: request.body.role,
email: request.body.email
}).then(function (users) {
if (users) {
response.send(users);
} else {
response.status(400).send('Error in insert new record');
}
});
});
app.listen(3000, function () {
console.log('Express server is listening on port 3000');
});
答案
你应该使用body-parser
https://www.npmjs.com/package/body-parser
示例使用body-parser:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:
')
res.end(JSON.stringify(req.body, null, 2))
})
例:
const Sequelize = require('sequelize');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json({ limit: '100mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '100mb', parameterLimit: 1000000 }));
const sequelize = new Sequelize('test_01', 'root', 'root', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
const users = sequelize.define('users', {
id: {
primaryKey: true,
type: Sequelize.INTEGER,
},
name: Sequelize.STRING,
role: Sequelize.STRING,
email: Sequelize.STRING
});
app.post('/test', function (request, response) {
return users.create({
id: request.body.id,
name: request.body.name,
role: request.body.role,
email: request.body.email
}).then(function (users) {
if (users) {
response.send(users);
} else {
response.status(400).send('Error in insert new record');
}
});
});
app.listen(3001, function () {
console.log('Express server is listening on port 3000');
});
以上是关于使用sequelize POST方法在nodejs中插入新记录的主要内容,如果未能解决你的问题,请参考以下文章
使用 Sequelize (NodeJS) 而不是 * 指定特定字段
Sequelize hasMany工作正常,但反比关系不正常