【问题标题】:Unable to trigger REST API to add records into MySQL DB无法触发 REST API 将记录添加到 MySQL 数据库
【发布时间】:2019-12-26 09:49:38
【问题描述】:

我在使用 Node.JS 和 Postman 向 MYSQL 插入数据时遇到问题

我创建了 3 个文件 - db.js、server_db.js、server.js。 Server.JS 是我们执行 GET/POST 时调用的主文件。我无法在 MYSQL DB 中插入任何记录。我正在遵循 Promise 代码 - 此处拒绝/响应。

  1. db.js-

    var mysql = require("mysql"); var db_config ={ host : '127.0.0.1', user : 'root', password : '*****', database : 'webapp' }; var connection; console.log("inside db.js 1") connection = mysql.createConnection(db_config); connection.connect(function(err){ if(err) throw err console.log('You are now connected..'); }); module.exports = connection;

server_db.js (此文件包含要触发的 SQL 查询,并在此处使用 Promises 来解析和拒绝)

var db = require('../db.js');
save_user_information = (data) => new Promise((resolve, reject)=>{
db.query('INSERT INTO lottery_information SET ?',data,function(err,results,fiels){
if(err){
reject('could not insert into lottery information');
}
resolve('Successful');
});
});
module_exports = {save_user_information};

服务器.js

我们从哪里调用 API

const express = require('express');
const app = express();
const bodyParser = require("body-parser");
const save_user_information = require('./models/server_db');
app.use(bodyParser.json());
app.post('/', async function(req, res){
var email = req.body.email;
var amount = req.body.amount;
if(amount <= 1){
return_info = {};
return_info.error = true;
return_info.message = "The amount should be greater than 1";
return res.send(return_info);
}
var result = await save_user_information({"amount" : amount, "email" : email});
res.send(result);
});
app.listen(3000, ()=>{
console.log('Server is running on port 3000');
});

我收到错误 -

(node:17568) UnhandledPromiseRejectionWarning: TypeError: save_user_information is not a function
at C:\GIT\Web2.0\server.js:41:23
at Layer.handle [as handle_request] (C:\GIT\Web2.0\node_modules\express\lib\router\layer.js:95:5)
at next (C:\GIT\Web2.0\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\GIT\Web2.0\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\GIT\Web2.0\node_modules\express\lib\router\layer.js:95:5)
at C:\GIT\Web2.0\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\GIT\Web2.0\node_modules\express\lib\router\index.js:335:12)
at next (C:\GIT\Web2.0\node_modules\express\lib\router\index.js:275:10)
at C:\GIT\Web2.0\node_modules\body-parser\lib\read.js:130:5
at invokeCallback (C:\GIT\Web2.0\node_modules\raw-body\index.js:224:16)
(node:17568) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:17568) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

因此,“save_user_information”似乎没有被视为功能。

你能告诉我哪里出错了。

【问题讨论】:

    标签: javascript mysql node.js express postman


    【解决方案1】:

    db.js - 该文件有mysql连接参数

    var mysql = require("mysql");
    var db_config ={
      host : '127.0.0.1',
      user : 'root',
      password : '****',
      database : 'webapp'
    };
    
    var connection;
    console.log("inside db.js 1")
    connection = mysql.createConnection(db_config);
    connection.connect(function(err){
      if(err) throw err
      console.log('You are now connected..');
    });
    

    server_db.js 这有查询参数

    console.log('inside server_db.js 1');
    var db = require('../db.js');
    var save_user_information = (data) => new Promise((resolve, reject)=>{
      db.query('INSERT INTO lottery_information SET ?',data,function(err,results,fiels){
        if(err){
          reject('could not insert into lottery information');
        }
        resolve('Successful');
      });
    });
    console.log('inside server_db.js 2');
    module.exports = {save_user_information};
    

    sever.js - 这是主文件

    const express = require('express');
    const app = express();
    const bodyParser = require("body-parser");
    const {save_user_information} = require('./models/server_db');
    app.use(bodyParser.json());
    app.post('/', async function(req, res){
      var email = req.body.email;
      var amount = req.body.amount;
    
    if(amount <= 1){
      return_info = {};
      return_info.error = true;
      return_info.message = "The amount should be greater than 1";
      return res.send(return_info);
    }
    
      var result = await  save_user_information({"amount" : amount, "email" : email});
      res.send(result);
    
      //res.send({"amount" : amount, "email" : email});
    
    });
    
    app.listen(3000, ()=>{
      console.log('Server is running on port 3000');
    });
    

    你必须定义变量。

    【讨论】:

      【解决方案2】:

      首先,要导出模块,您必须使用点,而不是下划线。 然后,在导出命名模块时,应将其作为命名模块导入。

      【讨论】:

      • 谢谢多梅卡。我使用 module.exports 进行了更改并将其导入,但仍然收到相同的错误。 const save_user_information = require('./models/server_db');
      • 如果你像 -module.exports = { save_user_information } 一样导出它,那么你必须像 - const { save_user_information } = require(...) 一样导入它
      • 谢谢多梅卡。我只使用过这样的导入 const {save_user_information} = require('./models/server_db');但代码中仍然存在错误。请指教
      • 请在更改后使用您现在的代码和错误更新 wuestion。
      • 嗨。我将 save_user_information 更改为功能,现在它工作正常,没有任何问题。再次感谢。这是一个小错误。非常感谢。
      猜你喜欢
      • 2019-10-23
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 2012-08-15
      相关资源
      最近更新 更多