尝试将POST请求数据传递到车把模板

时间:2019-12-16 15:55:04

标签: javascript express handlebars.js

我在玩快递和车把。我正在尝试使用Geolocation API发送带有用户的纬度和经度的发布请求。我可以将经纬度和经度长的值发送到服务器,但是我在弄清楚如何从发布请求中获取纬度和经度值到API请求中然后使用车把进行渲染时遇到了麻烦。下面的代码演示了我正在尝试执行的操作,但是在GET请求URL中使用了硬编码的纬度和经度值。

我的车把默认页面中的发布请求脚本

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <title>AvWx</title>
</head>
<body>

  <div class="container mt-4">
    {{{body}}}
  </div>

<script>
  let lat, long


  if (!navigator.geolocation) {
    console.log('No location data')
  } else {
    navigator.geolocation.getCurrentPosition(position => {
      lat = position.coords.latitude
      long = position.coords.longitude
      console.log(`Latitude: ${lat}, Longitude: ${long}`)
      let data = { lat, long }
      fetch('/latlong', {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
          'Content-Type': 'application/json'
        }
      })
    })
  }
</script>
</body>
</html>

快速路线

const express = require('express')
const app = require('../server')
const axios = require('axios')
const config = require('config')

const key = config.get('api')

// @route  GET home page
// @desc   Home page with handlebars
// @access Public
app.get('/', (req, res, next) => {
    // Trying to parse these lat and long values with user's position
    axios
        .get('https://api.checkwx.com/metar/lat/29/lon/-95/radius/50', {
            headers: { 'x-api-key': key }
        })
        .then(response =>
            res.render('main/index', {
                title: 'Weather App',
                weather: response.data.data
            })
        )
})

app.post('/latlong', (req, res) => {
    const { lat, long } = req.body

    if (!lat || !long) {
        res.status(400).json({ msg: 'No location found' })
    } else {
        // This request is working, but how do I get these values into the API request URL?
        console.log(`Lat: ${lat} Long: ${long}`)
    }
})

我要渲染的车把模板

<h1>{{title}}</h1>
<h4>Nearby Weather</h4>
<ul class="list-group">
  {{#each weather}}
    <li class="list-group-item">{{this}}</li>
  {{/each}}
</ul>

完整代码位于https://github.com/rawestmoreland/aviation-weather-handlebars

0 个答案:

没有答案