1.新建一个基于vue-cli3的一个项目,添加axios插件
vue create test
cd test
npm install axios
npm serve
2.编写带接口请求的页面

https://www.baidu.com/home/xman/data/tipspluslist是在百度页面扒的一个get请求,
此时运行起来会看到页面提示接口跨域

第一种:
此时使用vue.config.js文件(新建的vue项目没有vue.config.js文件需要自己手动创建)设置proxy代理来解决跨域问题
vue.config.js:
module.exports = { // 修改启动端口 devServer: { proxy: { '/home': { target: 'https://www.baidu.com', changeOrigin: true } }, disableHostCheck: true } }
展示的vue界面
<template>
<div class="hello">
<h1 @click="useApi">点我请求接口</h1>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'HelloWorld',
methods: {
useApi() {
axios.get('/home/xman/data/tipspluslist').then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
})
}
}
}
</script>
改完后需重新启动项目
可以看到接口请求成功了

第二种
设置nginx,使用nginx反向代理
1.打开nginx目录下的conf目录里面nginx.conf
2.修改nginx.conf的内容
首先我们知道前端请求链接是http://localhost:8081/,后端接口是https://www.baidu.com
然后配置nginx.conf
server { listen 3003; server_name localhost; location / { proxy_pass http://localhost:8081; } location /home { proxy_pass https://www.baidu.com; } }上面代码的意思是将localhost:3003转发为location:8081,也就是说现在访问localhost:3003实际上是访问location:5500,而访问localhost:3003/home则是访问https://www.baidu.com,并以home开头的url
配置好后要重启nginx(nginx -s reload)
3.打开http://localhost:3003/可以看到页面能成功打开,点击请求接口也能成功请求了

注意:
vue.config.js 中配置的代理只是解决了开发环境的跨域,上线时需要配置 nginx 代理
