使用Express& amp;插入记录sqlite3的

时间:2018-06-07 15:01:23

标签: express sqlite glitch-framework

我正在构建an app on glitch.com并尝试使用Express和SQLite3。

我的数据库中有两个表foodplaces,以及相应的表单。

应用程序设置为server.js运行数据库,client.js处理表单数据,但不写入数据库。

我查看了一些express和sqlite教程,但看不到如何将数据从表单发布到数据库。

server.js

// init sqlite db
var fs = require('fs');
var dbFile = './.data/sqlite.db';
var exists = fs.existsSync(dbFile);
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(dbFile, (err) => {
  if (err) {
    return console.error(err.message);
  }
  console.log('Connected to the in-memory SQlite database.');
});

if(exists) { 
  console.log("Database exists!");
}


  db.serialize(function(table, record){
  // construct the insert statement with multiple placeholders
        // based on the number of rows
        //let placeholders = table.map((record) => '(?)').join(',');
        var placeholders = '';
        switch(table) {
          case 'food':
            let sql = 'INSERT INTO food(fooditem,category,location, price) VALUES ' + placeholders;
            // output the INSERT statement
            console.log(sql); 
            db.run(sql, table, function(err) {
              if (err) {
                return console.error(err.message);
              }
              console.log(`Rows inserted ${this.changes}`);
            });
          case 'places':
            let query = 'INSERT INTO places(place) VALUES ' + placeholders;
            // output the INSERT statement
            console.log(sql); 
            db.run(query, table, function(err) {
              if (err) {
                return console.error(err.message);
              }
              console.log(`Rows inserted ${this.changes}`);
            });
          }

        // close the database connection
        db.close();

  }); 


  // if ./.data/sqlite.db does not exist, create it, otherwise print records to console
  db.serialize(function(){
    if (!exists) {
      db.run('CREATE TABLE food (fooditem TEXT, category TEXT, location INT, price TEXT); CREATE TABLE places (placename TEXT, address1 TEXT, address2 TEXT, address3 TEXT, placetype TEXT, map-ref TEXT)');
      console.log('New table food created!');

      // insert default food items
      db.serialize(function() {
        db.run('INSERT INTO food (fooditem,category,location, price) VALUES ("zucchini","shop", 1, "$5.50"), ("Tomatoes", "exchange", 2,"Zucchini"), ("Chokecherries", "forage", 3, "Free")');
      });
    }
    else {
      console.log('Database "food" ready to go!');
      db.each('SELECT * from food', function(err, row) {
        if ( row ) {
          console.log('record:', row);
        }
      });
    }
  });

// also included, a router and a listener

client.js 目前所做的一切都是从数据库中读取并将数据插入到html中的列表中,它不会将输入写入数据库。我尝试为此创建一个函数,但没有走得太远。

(function(){
  console.log('hello world :o');

    if(!(document.getElementById('addfooditem'))) {
     //do nothing
     } else {
        let food = [];

        // define variables that reference elements on our page
        const foodList = document.getElementById('food');
        const foodForm = document.getElementById('addfooditem');
        const fooditemInput = foodForm.elements['fooditem'];
        const place = foodForm.elements['entry-r1'];
        const price = foodForm.elements['price'];
        const type = foodForm.elements['type']; // sell, exchange, or forage

        // a helper function to call when our request for food is done
        const getFoodListener = function() {
          // parse our response to convert to JSON
          food = JSON.parse(this.responseText);

          // iterate through every fooditem and add it to our page
          food.forEach( function(row) {
            appendNewFooditem(row.fooditem);
          });
        }

         // request the food from our app's sqlite database
        const fooditemRequest = new XMLHttpRequest();
        fooditemRequest.onload = getFoodListener;
        fooditemRequest.open('get', '/getFood');
        fooditemRequest.send();

       // a helper function that creates a list item for a given fooditem
        const appendNewFooditem = function(fooditem, location, price, type) {
          const newListItem = document.createElement('li');
          newListItem.innerHTML = fooditem + ', ' + price  + ' (' + location + ' - '+ type + ')';
          foodList.appendChild(newListItem);
        }

          // listen for the form to be submitted and add a new fooditem when it is
        foodForm.onsubmit = function(event) {
          // stop our form submission from refreshing the page
          event.preventDefault();

          // get fooditem value and add it to the list
          food.push(fooditemInput.value, place.value, price.value, type.value);
          appendNewFooditem(fooditemInput.value, place.value, price.value, type.value);
          var record = fooditemInput.value + ',' + place.value + ',' +  price.value + ',' +  type.value;

          // reset form 
          fooditemInput.value = '';
          place.value = '';
          price.value = '';
          fooditemInput.focus();
          //addListing('food', record);
        };
     }

client.js如何将表单数据发送到server.js?是否有任何遗漏(没有模型和控制器文件)?

0 个答案:

没有答案