效果
具体操作
天气查询API服务地址:
URL | https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=<用户key> |
请求方式 | GET |
在vue.config.js中配置proxy,解决项目中跨域问题
devServer: {
host: "0.0.0.0",
port: port,
open: true,
proxy: {
"/api": {
target: "https://restapi.amap.com",
changeOrigin: true,
pathRewrite: {
"^/api": "",
},
},
},
disableHostCheck: true,
},
封装接口
import axios from "axios";
const instance = axios.create({
baseURL: "/api",
timeout: 10000,
});
export function get(url, params) {
return instance.get(url, { params });
}
export function getWeather() {
return get("/v3/weather/weatherInfo", {
city: " ", //城市代码
key: " ", //高德KEY
});
}
组件中调用接口
import { getWeather } from "@/api/weather.js";
mounted(){
getWeather().then((res) => {
console.log('天气',res.data.lives[0])
});
}