[英]Pass data from Vue front end to Node/Express backend
我希望用戶能夠在“/”路線的文本輸入中輸入城市。 提交后,id 喜歡重定向到“/result”並顯示信息。 我可以讓'/result'顯示我想要的唯一方法是,如果我在后端硬編碼一個城市。 我該如何消除這個?
獲取請求
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>
你可以像這樣傳遞一些參數
axios.get('/result', {
params: {
city: 'Portland'
}
})
當然,這需要轉發到您的 function 以使其動態化。
您還可以使用一些標頭或發出POST
請求而不是GET
。 不確定所有這些解決方案之間的真正區別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.