前端页面访问后端接口,分为两种情况:
- 前端页面和后端代码在同一个项目中:常用ajax
- 前端项目和后端项目不属于同一个项目:vue项目中使用axios
ajax
jquery实现Ajax
跨域访问
- 跨域访问理解:通常,网络地址是由三部分组成的:协议://ip地址:端口号。当前端所要访问的后端的网络地址地址和前端工程的网络地址的协议或者ip或者端口号中有一个不一样,则访问后端时便属于跨域访问。
- Vue项目实现跨域访问:基于axios实现。
- 通过学习axios,我们知道,axios是用来实现像后端发送请求的。
- 在普通的html文件中使用axios的方法我已经介绍过了axios基本使用传送门
- 下面主要讲如何在vue项目(通过vue命令创建的项目)中使用axios
axios使用
- 使用axios实现跨域访问,为了测试是否成功,必须要有后端接口。如果我们没有写好的后端代码,则可以使用网上的API,比如聚合数据
网络数据API使用方法(以聚合数据为例)
- 首先,注册账号并且登录
- 登陆后,里面有免费数据也有收费的数据,我们以免费数据为例
- 点击导航栏中"API"
- 点击后,可以看到各种类型的数据,选择需要的数据,我们以IP地址为例
- 如果没有进行实名认证,则需要实名认证后才能使用
- 点击使用,找到API测试工具
- 我们需要使用到接口地址,请求方式,“值”处是我们的请求参数,使用者手动输入,点击发送请求可以获得json格式的数据。
Vue项目使用axios
-
安装axios
npm install axios --save
-
在vue文件中的
<script><script>
中导入:即添加两句代码:import VueAxios from 'vue-axios'
import axios from 'axios'
<script>
import VueAxios from 'vue-axios'
import axios from 'axios'
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
- 配置域名代理
找到config-index.js文件,在文件中找到proxyTable,配置域名信息。举例如下:
’ /taobao’:代表axios中url要使用的域名
targer代表域名具体要访问的地址:即http://localhost:8080/toutiao表示访问的http://v.juhe.cn/toutiao/index
proxyTable: {
'/toutiao':{
target:'http://v.juhe.cn/toutiao/index',
changeOrigin: true,
pathRewrite: {
'^/toutiao': ''
}
}
},
- 和普通的axios一样,书写axios语句:
例如给按钮添加点击事件,实现查询功能
<!--html代码 -->
<button @click="select">头条</button>
//vue方法
select(){
axios({
url:'/toutiao?type=%E7%96%AB%E6%83%85&key=51c5d6b69f63c8b70c4d71623de8eba1',
method:'GET'
}).then((response)=>{
var res = response.data;
console.log(res);
})
}
具体实例
index.js
proxyTable: {
'/toutiao':{
target:'http://v.juhe.cn/toutiao/index',
changeOrigin: true,
pathRewrite: {
'^/toutiao': ''
}
}
},
HelloWorld.vue
<template>
<div>
....
<button @click="select">头条</button>
</div>
</template>
<script>
import VueAxios from 'vue-axios'
import axios from 'axios'
export default {
name: 'HelloWorld1',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
methods: {
select(){
axios({
url:'/toutiao?type=%E7%96%AB%E6%83%85&key=51c5d6b69f63c8b70c4d71623de8eba1',
method:'GET'
}).then((response)=>{
var res = response.data;
console.log(res);
})
}
},
}
</script>
参考文章:
https://blog.csdn.net/qq_34305040/article/details/80146009?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-2&spm=1001.2101.3001.4242