【问题标题】:Rest API: Inserting value to MySQL database with ExpressJSRest API:使用 ExpressJS 将值插入 MySQL 数据库
【发布时间】:2018-11-09 00:01:09
【问题描述】:

我在 ExpressJS 上运行了这个简单的 MySQL 数据库 API。

const express = require('express');
const router = express.Router();

const app = express();
const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Listening on port ${port}`));

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'andri',
  password: '12345',
  database: 'andri'
});

app.get('/employees', function (req, res) {
  console.log(req);
  connection.query('select * from users', function (error, results, fields) {
    if (error) throw error;
    res.end(JSON.stringify(results));
  });
});

app.get('/employees/:id', function (req, res) {
  connection.query('select * from users where id=?', [req.params.id], function (error, results, fields) {
    if (error) throw error;
    res.end(JSON.stringify(results));
  });
});

app.post('/employees', function (req, res) {
  var postData = req.body;
  connection.query("INSERT INTO users (`id`, `userid`, `fullname`, `usergroup`, `emailid`, `mobile`, `title`, `created_at`) VALUES (NULL, '?', '?', '?', '?', '?', '?', CURRENT_TIMESTAMP);", 
  postData, function (error, results, fields) {
    if (error) throw error;
    res.end(JSON.stringify(results));
  });
});

我可以使用 POSTMAN 测试 GET 函数(员工/和员工/:id)端点工作正常。但是POST功能

{
    "userid": "PROJ-12345",
    "fullname": "Eko Andri S",
    "usergroup": "IT",
    "emailid": "eko.andri@xxx.or.id",
    "mobile": "0811111111",
    "title": "Intern",
    "created_at": "2018-05-30T01:59:17.000Z"
}

在 POTSMAN 上得到这个结果:

{
    "fieldCount": 0,
    "affectedRows": 1,
    "insertId": 8,
    "serverStatus": 2,
    "warningCount": 0,
    "message": "",
    "protocol41": true,
    "changedRows": 0
}

以上记录成功记录在数据库中,但每个字段的值为“?”没有报价;除了正确记录的时间戳。

如果我删除 ?在 INSERT 行中,我收到以下错误

您的 SQL 语法有错误

【问题讨论】:

  • 感谢您的帮助,但我尝试了许多组合,它说“您的 SQL 语法有错误”。此语法不起作用“INSERT INTO users, [postData.id, postData.userid,etc] VALUES [NULL,'?','?',...]。你能更具体我应该在? 标记。谢谢
  • 查看库中的示例,(它们不会在 ? 周围添加引号,并且它们还将数组作为第二个参数而不是对象传递,也就是说,我想说的是)
  • 好的,谢谢,我会调查的。

标签: mysql node.js rest express


【解决方案1】:

看来,您缺少 解析使用 HTTP POST 请求提交的 JSON、缓冲区、字符串和 URL 编码数据的正文解析器部分。您可以找到有关 body-parser 的更多信息here

在您的代码中添加以下行并确保您已安装 body-parser。

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); 

然后在你的app.post 部分

app.post('/employees', function (req, res) {
  var postData = req.body;
  postData.created_at = new Date();
  connection.query("INSERT INTO users SET ?",
  postData, function (error, results, fields) {
    if (error) throw error;
    console.log(results.insertId); // Auto increment id
    res.end(JSON.stringify(results));
  });
});

希望它会起作用。

【讨论】:

  • 嗨,Deepak,它运行良好。抱歉,我刚从学校回来,回复晚了。
【解决方案2】:

由于 问号 (?) 用单引号括起来,它被视为一个字符串,这就是为什么 问号 (?) 会存储在您的数据库中。结帐以下方法通过插入具有自动增量主键的行来实现。

app.post('/employees', function (req, res) {
  var postData = req.body;
  connection.query("INSERT INTO users SET ?", 
  postData, function (error, results, fields) {
    if (error) throw error;
    console.log(results.insertId); // Auto increment id
    res.end(JSON.stringify(results));
  });
});

【讨论】:

  • 您能否在发布请求时删除 created_at 字段并告诉我。如果出现错误,请与完整的跟踪分享。
猜你喜欢
  • 2020-11-23
  • 2023-04-01
  • 2023-02-02
  • 1970-01-01
  • 2018-05-09
  • 2021-02-13
  • 2020-03-29
  • 1970-01-01
  • 2018-01-27
相关资源
最近更新 更多