前言
在 vue cli4 搭建的 vue 项目中,用 node.js+express 搭建中间层服务器(解决 axios 请求出现的跨域问题),利用 axios 的 get请求第三方接口(需要key),实现输入地区查询天气——
提示:以下是本篇文章正文内容,下面案例可供参考
一、nodejs+express搭建中间层
package.json 文件配置:
{
"name": "server",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.21.1",
"cors": "^2.8.5",
"ejs": "^3.1.6",
"express": "^4.17.1",
"http-proxy-middleware": "^1.0.6"
},
"devDependencies": {},
"description": ""
}
app.js 文件配置:
//导入express框架
const express = require("express");
//导入axios插件
const axios = require("axios");
//初始化express
const app = express();
//本地服务器解决跨域,不可缺
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
//Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', '*');
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
//get接口访问,访问自己这个服务器接口
app.get("/getlist", function (req, res) {
//服务器获取数据,将不会产生跨域问题
axios.get("https://api.apishop.net/common/weather/get15DaysWeatherByArea",
{
params: {
apiKey: 'dCHrki31e9eb5d96e76a59d62...', //apishop官网提供的apiKey
area: req.query.area // 接收前端传来的地区参数
}
})
.then((response) => {
//以json格式将服务器获取到的数据返回给前端。
res.json(response.data);
})
})
//启动server,端口3000
var server = app.listen(3000, function () {
console.log("开启成功!");
})
注:需要 cnpm i 初始化配置
二、vue页面
以下为vue中的一个组件:
<template>
<div>
<input type="text" v-model="inputCity" @keypress="enter">
<div>
{{ month }} 月 {{ day }} 日
<hr>
{{ city }}
{{ tem }}℃
<hr>
<img :src="pic" alt="">
</div>
</div>
</template>
<script>
export default {
data() {
return {
inputCity: '',
city: '',
tem: '',
month: '',
day : '',
pic: '',
};
},
methods: {
enter() {
this.$axios.get("http://localhost:3000/getlist",{ //请求node.js服务端
params: {
area: this.inputCity // 传参 area,即输入的地区名
}
})
.then((res) => {
console.log(res);
let arr = res.data.result.dayList;
this.pic = arr[0].day_weather_pic
this.city = arr[0].area
this.tem = arr[0].day_air_temperature
let time = arr[0].daytime
this.month = time.slice(4,6)
this.day = time.slice(6)
})
.catch((err) => {
console.log(err);
});
}
},
};
</script>
<style>
</style>
效果图
初始状态:
输入查询城市: