我希望用户能够在“/”路线的文本输入中输入城市。提交后,id 喜欢重定向到“/result”并显示信息。我能得到 '/result' 来显示我想要的唯一方法是如果我在后端硬编码一个城市。我该如何消除这种情况?
GET 请求
app.get('/result', (req, res) => {
let city = 'Portland';
let url = `${process.env.BASEURL}${city}&units=imperial&APPID=${process.env.API_KEY}`;
axios.get(url)
.then(response => { res.json(response.data) })
.catch(error => {
return res.status(500).json({
success: false,
message: error.message
})
});
});
从后端 API 传递数据的服务文件
import axios from 'axios';
const url = "http://localhost:5000/result";
class WeatherService {
static getWeather() {
return new Promise((resolve, reject) => {
axios.get(url).then((res) => {
try {
resolve(res.data);
} catch (error) {
reject(error);
}
})
})
}
}
export default WeatherService;
前端
<template>
<div>
<p class="error" v-if="error">{{ error }}</p>
<i class="fa fa-times close-icon none"></i>
<main>
<div class="location none">
<div class="city">{{ weather.name }}</div>
<div class="long-lat">{{ weather.coord.lon }}, {{ weather.coord.lat }}</div>
<div class="date">-, -:- pm</div>
</div>
<div class="main-content none">
<div class="tempIcon">
<div class="condition-icon"></div>
<div class="temp">{{ weather.main.temp }}<span>°</span></div>
</div>
<div class="weather">{{ weather.weather[0].main }}</div>
<div class="hi-low">{{ weather.main.temp_max }}° / {{ weather.main.temp_minl }}° <span></span>Feels like {{ weather.main.feels_like }}°</div>
</div>
</main>
<section class="details">
<div class="humidity none">
<i class="fa fa-tint"></i>
<h5>Humidity</h5>
<p class="humidity-value">{{ weather.main.humidity }}%</p>
</div>
<div class="pressure none">
<i class="fa fa-tachometer"></i>
<h5>Pressure</h5>
<p class="pressure-value">{{ weather.main.pressure }} hPa</p>
</div>
<div class="wind none">
<i class="fa fa-wind"></i>
<h5>Wind</h5>
<p class="wind-value">{{ weather.wind.speed }} mph</p>
</div>
</section>
</div>
</template>
<script>
import WeatherService from '../WeatherService';
export default {
name: 'Result',
data(){
return {
weather: [],
error: ''
}
},
async created() {
try {
this.weather = await WeatherService.getWeather();
} catch (error) {
this.error = error.message;
console.log(error);
}
}
}
</script>
答案 0 :(得分:1)
你可以像这样传递一些参数
axios.get('/result', {
params: {
city: 'Portland'
}
})
当然,这需要转发到您的函数以使其动态化。
您还可以使用一些标头或发出 POST
请求而不是 GET
。不确定所有这些解决方案之间的真正区别。