尝试循环遍历json文档,并使用NODE.js将一些数据插入sql数据库的新行中

时间:2018-11-27 23:06:43

标签: mysql node.js json express

App.js连接到数据库,并且在一条路径上具有GET / POST。我正在使用https://www.reddit.com/r/DMT.json

中的JSON数据
let mysql = require('mysql2');
let dbInfo = require('./dbInfo.js');
let express = require('express');
let bodyParser = require("body-parser");
let redditdata = require('./cit381-assign07-reddit.json');
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());

// Select all rows
app.get('/reddit-import/:post_ID?', function (req, res) {
   console.log("Route /reddit-import GET", req.params);
   let data = [];
   let sql = "SELECT * FROM POSTS";
   if (req.params.post_ID != undefined) {
      sql += " WHERE post_ID = ?";
      data = [req.params.post_ID];
      // Object technique:
      // sql += " WHERE ?";
      // data = req.params;
      console.log(data);
   } else {
      sql += " ORDER BY post_ID";
   }
   console.log("SQL", sql);
   connection.query(sql, data,
      function (errQuery, rows) {
         if (errQuery) {
            console.log(errQuery);
            res.json({rows: [], err: errQuery});
         } else if (rows) {
            console.log("Rows returned", rows.length);
            res.json({rows: rows, err: ""});
         } else {
            console.log("No post rows...\n");
            res.json({rows: [], err: ""});
         }
      }
   );
});

// Add a new row from json
app.post('/reddit-import', function (req, res) {
   console.log("Route /reddit-import POST");
   let obj = JSON.parse(redditdata);
   let data = {title: req.body.title, created_utc: req.body.created_utc, score: req.body.score, num_comments: req.body.num_comments, num_crossposts: req.body.num_crossposts, url: req.body.url, permalink: req.body.permalink};
   connection.query("INSERT INTO POSTS SET ?",
      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: ""});
         }
      }
   );
});

// Handle missing pages requested using GET HTTP verb
app.get('*', function(req, res) {
   res.status(404).send('Sorry that page does not exist');
});

// 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 JSON server app listening on port ' + port);
         } catch (err) {
            console.log(err);
         }
      });
   }
});

我正在努力让应用程序遍历整个JSON文件以插入新行。 JSON文件的每个新帖子都有嵌套部分,我希望将每个帖子中的数据插入到我的数据库表中。我能够连接到数据库,app.get可以正常工作,并且尝试插入单个帖子(app.post)也可以。我将如何设置它以解析或循环遍历整个JSON文件并为每个帖子创建一个新行?我是node.js和express的新手,所以我不确定如何在express应用中合并javascript循环。我使用Postman调用应用程序。

0 个答案:

没有答案