app.js 1.8 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');

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.'
    });
  }
})

app.post('/food', 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 rand = Math.floor(Math.random() * 3); //(Math.random() * (max - min)) + min
      var i = 0;
      for (var foods in users) {
        if (rand == i) {
          var food_value=foods;
          // $('<li>').text(foods).appendTo('#users');
        }
        i++;
      }

      console.log(rand);
      res.render('print.ejs', {
        title: 'Recommendation',
        description: 'We recommend this...',
        // name: users,
        randvalue: food_value
      });
    }
  });
})

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