无法将所有数据插入MySQL表

时间:2018-11-29 05:14:33

标签: javascript mysql reactjs express postman

我正在一个项目中,目标是从subreddit解析JSON文件并将该文件中的信息放入MySQL数据库中的表中。我正在使用NodeJS和Express服务器创建一个REST API。我有两个表,用户和帖子,只能在表中获取3个用户名,但没有帖子信息,也没有3岁以上的用户。我已经调试了几个小时,完全迷路了。我不需要任何人为我完成这项任务,但是很乐意为解决此问题提供建议或技术。

//jshint esversion: 6
let mysql = require("mysql2");
let dbInfo = require("./dbInfo.js");
let express = require("express");
let bodyParser = require("body-parser");

let app = express();

// Add static route for non-Node.js pages
app.use(express.static("public"));

// Configure body parser for handling post operations
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

// Add reddit
app.post("/reddit-import", function(req, res) {
  console.log("Route /reddit-import POST");
  let x = req.body;
  console.log(x);
  for (let i = 0; i < x.data.children.length; i++) {
    let users_data = {
      username: x.data.children[i].data.author
    };
    console.log(x.data.children[i].data.author);
    let post_data = {
      author: x.data.children[i].data.author,
      created_utc: x.data.children[i].data.created.utc,
      score: x.data.children[i].data.score,
      title: x.data.children[i].data.title,
      url: x.data.children[i].data.url,
      num_comments: x.data.children[i].data.num_comments,
      num_crossposts: x.data.children[i].data.num_crossposts,
      permalink: x.data.children[i].data.permalink
    };
    connection.query("INSERT INTO USERS SET ?", users_data, function(errQuery, result) {
      if (errQuery) {
        console.log(errQuery);
        res.json({status: "Error", err: errQuery});
      } else {
        console.log("Insert ID: ", result.insertId);
        res.json({status: result.insertId, err: ""});
      }
    });
  }
});

// Create database connection
console.log("Creating connection...\n");
let connection = mysql.createConnection({host: dbInfo.dbHost, port: dbInfo.dbPort, user: dbInfo.dbUser, password: dbInfo.dbPassword, database: dbInfo.dbDatabase});
// Connect to database
connection.connect(function(err) {
  console.log("Connecting to database...\n");

  // Handle any errors
  if (err) {
    console.log(err);
    console.log("Exiting application...\n");
  } else {
    console.log("Connected to database...\n");
    // Listen for connections
    // Note: Will terminate with an error if database connection
    // is closed
    const ip = "localhost";
    const port = 8080;
    app.listen(port, ip, function() {
      try {
        console.log("Reddit-import server app listening on port " + port);
      } catch (err) {
        console.log(err);
      }
    });
  }
});

0 个答案:

没有答案