【发布时间】:2021-05-27 07:22:18
【问题描述】:
我在后端创建了一个 api,并在 http://localhost:5000/result 上以 JSON 格式显示结果。我发现我需要一个 .js 文件来处理 api 并允许我在我的 Vue 组件中使用数据。这是我找到的解决方案:
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 {
const data = res.data;
resolve(
data.map(weather => ({
...weather
}))
);
} catch (error) {
reject(error);
}
})
})
}
}
export default WeatherService;
我的 Vue 组件
<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;
}
}
}
</script>
启动两者后,我得到data.map is not a function 并且无法使用任何数据。
编辑:我现在意识到 .map() 用于数组,我正在尝试将它用于 JSON 数据。什么是类似的解决方案?
编辑 2:Json 数据
{
"coord": {
"lon": -97.7431,
"lat": 30.2672
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 82.15,
"feels_like": 81.23,
"temp_min": 80.01,
"temp_max": 84.2,
"pressure": 1015,
"humidity": 37
},
"visibility": 10000,
"wind": {
"speed": 3.44,
"deg": 0
},
"clouds": {
"all": 1
},
"dt": 1614206313,
"sys": {
"type": 1,
"id": 3344,
"country": "US",
"sunrise": 1614171738,
"sunset": 1614212779
},
"timezone": -21600,
"id": 4671654,
"name": "Austin",
"cod": 200
}
【问题讨论】: