首页 > 解决方案 > 如何将两个 GET 请求/数据库合并为 1?

问题描述

我想将天气 API 与您在其中填写心情的表格结合到 1 个应用程序中:您填写所在城市(以便您了解天气)和填写当天心情的表格。

在我的 server.js 文件中,我有两个 GET 和两个 POST 函数。但是,我想我只能使用 res.render('index',...) 一次。如何将两个 GET 功能组合成 1 个工作功能?

server.js 文件

const express = require('express')
const app = express()
app.use(express.static('./public'))  

// --> npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// --> npm install ejs 
app.set('view engine', 'ejs');

// --> npm install request
// --> npm install request-promise
const request = require('request-promise');

// --> npm install mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://MONGO_HOST/test?retryWrites=true&w=majority');

// apiKey
const apiKey = 'XXX';

// database weather
var citySchema = new mongoose.Schema({
  city: String
});
var cityModel = mongoose.model('City', citySchema); 

// database mood
var moodSchema = new mongoose.Schema({     
  name: String, 
  description: String,
  date: String
});
var moodModel = mongoose.model('Mood', moodSchema);    

// function which gets a list of moods in the database  
async function getDiary(moods) {
  var diary_data = [];

  for (var mood_obj of moods) {
    var name = mood_obj.name;
    var description = mood_obj.description;
    var date = mood_obj.date;

    var diary = {
      name : name, // variable declared above
      description : description, // variable declared above
      date : date // variable declared above
    };

    diary_data.push(diary);
  }

  return diary_data;
};

// GET route mood
app.get('/', function (req, res) {
  moodModel.find({}, function(err, moods){

    console.log(moods);                         
    getDiary(moods).then(function(results){     

      var diary_data = {diary_data: results};
      res.render('index', diary_data);
    })
  });
}) 

// function which gets a list of cities in the database  
async function getWeather(cities) {
  var weather_data = [];

  for (var city_obj of cities) {
    var city = city_obj.name;
    var url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${apiKey}`;

    var response_body = await request(url);

    var weather_json = JSON.parse(response_body);

    var weather = {
      city : city, // variable declared in this document 
      temperature: weather_json.main.temp,  // variable from API data
      description : weather_json.weather[0].description, // variable from API data
      icon : weather_json.weather[0].icon, // variable from API data
    };

    weather_data.push(weather);
  }

  return weather_data;
};

// GET route weather
app.get('/', function (req, res) {
  cityModel.find({}, function(err, cities){

    console.log(cities);

    getWeather(cities).then(function(results){

      var weather_data = {weather_data: results};
      res.render('index', weather_data);

    })
  });
})

// POST route mood
app.post('/', function(req, res) {        
  var newMood = new moodModel({
    name: req.body.mood_name, 
    description: req.body.mood_description,
    date: req.body.mood_date
  });
  newMood.save();                           

  res.redirect('/');
})

// POST route weather
app.post('/', function(req, res) {
  var newCity = new cityModel({city: req.body.city_name});
  newCity.save();

  res.redirect('/');
});

// setup port
const port = 3000;

app.listen(port, function() {
  console.log(`server is listening on port ${port}`);
})

index.ejs 文件

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test</title>
    <link rel="stylesheet" type="text/css" href="/css/style.css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
  </head>

  <body>

    <div class="container">

      <% for (diary of diary_data) { %>
      <div class="moodBox">
        <span class="title"><%= diary.name %></span>
        <br>
        <span class="title"><%= diary.description %></span>
        <br>
      </div>
      <% } %>


      <% for (weather of weather_data) { %>
      <div class="weatherBox">
          <span class="title"><%= weather.city %></span>
          <br>
          <span class="subtitle"><%= weather.temperature %></span>
          <br> <%= weather.description %>
      </div>
      <% } %>


      <fieldset>
        <form method="post" action="/">
          <div>
            <label for="mood_name">mood name</label>
            <input type="text" name="mood_name" required>
          </div>

          <div>
            <label for="mood_description">mood description</label>
            <input type="text" name="mood_description" required>
          </div>

          <div>
            <input type="date" name="mood_date">
            <div id="theDate"></div>
          </div>

          <div>
            <label for="city_name">City name</label>
            <input type="text" name="city_name">
          </div>

          <button type="submit">Submit</button>      

        </form>
      </fieldset>

    </div>
  <script src="/extra.js"></script>
  </body>
</html>

标签: node.jsexpressbody-parser

解决方案


推荐阅读