巴中网站建设培训班百度分析
1.安装axios库,用其处理http请求
npm install axios --save
2.因为vue和koa是两个不同的服务,使用cors处理跨域问题
安装koa-cors插件
npm i koa-cors -S
代码处理资源共享
let cors = require('koa-cors');
// 处理跨域
app.use(async (ctx, next) => {
ctx.set("Access-Control-Allow-Origin", "*")
await next()
})
3.写个get接口测试
router
.get('/getJson', async ctx => {
// 返回给前端的数据
ctx.body = 'shaelyn666';
});
4.Home.vue中调用接口
created() {
const axios = require("axios")
let self = this;
// Make a request for a user with a given ID
axios
.get("http://127.0.0.1:3000/getJson")
.then(function (response) {
// handle success
console.log('结果:',response)
self.str = response.data
})
.catch(function (error) {
// handle error
console.log(error)
})
.then(function () {
// always executed
})
}
5.浏览器控制台查看接口返回数据
控制台打印结果.png
状态200,成功调用接口