SHARE
TWEET

Untitled

a guest May 23rd, 2018 140 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var express = require('express');
  2. var app = express();
  3. var bodyParser = require('body-parser');
  4.  
  5. app.use(express.static('./'));
  6. app.use(bodyParser.urlencoded({ extended: true }));
  7.  
  8. var mysql = require('mysql');
  9. var connection = mysql.createConnection({
  10.     host : ' ',
  11.     user: 'root',
  12.     password: '',
  13.     database: 'test'
  14. });
  15.  
  16. connection.connect();
  17.  
  18. app.get('/',(req,res) => {
  19.     res.send("Hello try at /books");
  20. });
  21.  
  22.  
  23. app.get('/books',function(req,res){
  24.     var {keyword} =req.query;
  25.     connection.query('SELECT * FROM books WHERE title LIKE ?','%'+keyword+'%', function (error, results, fields) {
  26.         if (error){
  27.             throw error;
  28.             alert("Book not found");
  29.         }
  30.         for(let result of results){
  31.             console.log(result);
  32.                
  33.             }
  34.             res.send(results);
  35.        
  36.     });
  37. });
  38.  
  39. app.post('/books',function(req,res){
  40.     var title = req.body.title;
  41.     var author = req.body.author;
  42.     var genre = req.body.genre;
  43.     var price = req.body.price;
  44.     connection.query('INSERT INTO books (author,title,genre,price) VALUES (?, ?, ?, ?)', [author, title, genre, parseFloat(price)],function(error,results,fields){
  45.         if(error){
  46.             throw error;
  47.             alert("Could not add book, check if price is number")
  48.         }else{
  49.             res.send("book added");
  50.         }
  51.        
  52.     });
  53.    
  54. });
  55.  
  56.  
  57. app.listen(3000);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top