app.js 2.89 KB
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require("fs");

app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.urlencoded({
  extended: false
})); //post에서bodyparser로 받기 위함
app.set('views', __dirname + '/views');
app.set('views engine', 'ejs');


//main page
app.get(['/food', '/food/:id'], function(req, res) {
  var id = req.params.id;
  if (id) {
    if (id == 'search') {
      res.render('search.ejs', {
        title: 'Searching',
        description: 'You can search for food here.'
      });
    } else if (id == 'recommendation') {
      res.render('recommendation.ejs', {
        title: 'Recommendation',
        description: 'Enter the conditions you want.'
      });
    }
  } else {
    res.render('index.ejs', {
      title: 'Welcome',
      description: 'Hello, Here is our homepage.'
    });
  }
})

//사용자가 호출한 search page
app.post('/food/search', function(req, res) {
  var title=req.body.title;
  res.redirect("https://www.google.com/search?q="+title+"&oq="+title+"&aqs=chrome..69i57j0l3j69i60j69i61.3149j0j9&sourceid=chrome&ie=UTF-8")
})

//사용자가 호출한 recommendation page
app.post('/food/recommendation', function(req, res) {
  fs.readFile('data/food.json', 'utf8', function(err, data) {
    if (err) {
      console.log((err));
      res.status(500).send('Internal Server Error');
    } else {
      var users = JSON.parse(data);
      var price = req.body.price;
      var shape = req.body.shape;
      var kinds = req.body.kinds;
      var list = {
        food: []
      };
      for (var foods in users) {
        if ((!price || users[foods]['price'] == price) && (!shape || users[foods]['shape'] == shape) && (!kinds || users[foods]['kinds'] == kinds)) {
          list.food.push(foods);
        }
      }
      fs.writeFile('data/temp.json', JSON.stringify(list), "utf8", function(err) {
        if (err) {
          console.log(err);
          res.status(500).send('Internal Server Error');
        }
      });

      fs.readFile('data/temp.json', 'utf8', function(err, data) {
        if (err) {
          console.log((err));
          res.status(500).send('Internal Server Error');
        } else {
          var food = JSON.parse(data)['food'];
          var length=food.length;
          var rand = Math.floor(Math.random() * length); //(Math.random() * (max - min)) + min
          for (var i = 0; i < length; i++) {
            if (rand == i) {
              var food_value = food[i];
              break;
              // $('<li>').text(foods).appendTo('#users');
            }
          }
          res.render('print.ejs', {
            title: 'Recommendation',
            description: 'We recommend this...',
            randvalue: food_value
          });
        }
      });
    }
  });
})


app.listen(3000, function() {
  console.log('Connected, 3000');
})