目录
项目创建
代码
解决跨域问题
几个注意点
运行结果展示
axios官方文档:起步 | Axios 中文文档 | Axios 中文网
项目创建
本文实例用到的两个项目,分别命名为server和vue-axios。
server是node.js项目,创建方式:
# 创建server并打开位于该文件夹下的终端
# 初始化项目
npm init
# 然后输入包名 server,然后无脑回车即可# 安装模块包
npm install express --save# 创建文件 index.js# 开启服务器,注意每次修改index.js都要重新开启才生效!!
node index.js
vue-axios是vue3项目,我使用vite创建,当然你也可以用vue-cli:
# 进入根目录终端 使用vite创建项目 名称为vue-axios
npm create vite@latest vue-axioscd vue-axios
npm install# 使用npm安装axios插件
# 也可以使用yarn等等,详见开头的官方文档
npm install axios# 运行npm run dev
以上步骤都完成后,接下来以三个例子说明axios请求数据,分别是get、post请求本地服务器,还有向外部服务器(以斗鱼为例)发起请求。
代码
1. vue-axios/src/App.vue
<template><button @click="getReq">发送一个 get 请求</button><button @click="postReq">发送一个 post 请求</button><button @click="douClick">请求斗鱼服务器</button><!-- 以下是从斗鱼服务器请求数据的展示 --><ul><li v-for="item in state.dy" :key="item.room_id"><img :src="item.room_src" alt=""><h4>{{ item.room_name }}</h4></li></ul>
</template>
<script setup>
// 导入
import axios from 'axios';
import { reactive } from "vue";let state = reactive({});// 发送 get 请求
let getReq = () =>{axios.get("http://localhost:3030/getUser?name=张三").then(function (response){// 处理成功的情况console.log(response.data)}).catch(function (error){// 请求失败console.log(error);}).then(function() {// 总是会执行})
}
// 发送 post 请求
let postReq =() =>{let data ={name:"李四"};axios.post('http://localhost:3030/postUser', data).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});
}
let douClick = ()=>{// http://open.douyucdn.cn/api/RoomApi/liveaxios.get('/api/RoomApi/live').then((res)=>{console.log(res.data.data);state.dy = res.data.data;}).catch((error)=>{console.log(error);}).then(()=>{})
}
</script><style scoped></style>
2. server/index.js
// 服务器入口文件// nodejs里用require来进行导入一个模块的函数
const express = require('express')// 通过 express 创建一个应用对象app
const app = express()// 解决post请求获取请求体的问题
app.use(express.json());
app.use(express.urlencoded({extended: true
}))app.get('/getUser',(req,res)=>{// 在这里是处理接口的方法,可以在数据库中查询内容console.log(req.query);// 解决跨域问题res.set("Access-Control-Allow-Origin","*");// res.send 将数据发送给前端res.send({name: req.query.name,age: 18,sex:true})
})
app.post('/postUser',(req,res)=>{console.log(req.body);// 解决跨域问题res.set("Access-Control-Allow-Origin","*");res.send({name:'李四',age: 11})
})app.listen('3030',()=>{// localhost 本机地址// 127.0.0.1 本机ipconsole.log('服务器开启成功,地址');
})
解决跨域问题
在前端解决:
修改vue文件根目录里的vue-axios/vite.config.js(如果是用vue-cli创建的就是vue.config.js)
其中'/api'是你要访问的服务器api,在此处定义后,你axios里对这个api发起的请求就不会出现跨域问题。
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'// https://vitejs.dev/config/
export default defineConfig({plugins: [vue()],server:{proxy:{'/api':'http://open.douyucdn.cn/'}}
})
如果是vue.config.js是这样写的的
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8081/api', // 你自己的api接口地址
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': '',
}
}
}
}
原文链接:https://blog.csdn.net/qq_26780317/article/details/119647250
在服务器解决:
就是在每个请求方法里都加上这一句:
res.set("Access-Control-Allow-Origin","*");
这些方法发起的请求就不会出现跨域问题。
几个注意点
(1)vue文件要记得在使用axios的代码之前导入axios。
(2)发送post请求前需要URLSearchParams对数据进行处理,否则就算解决了跨域问题也无法得到响应。
报错如下:
Access to XMLHttpRequest at。。。has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
(3)向本地服务器发起请求,前端和服务器项目都要保持运行状态,修改了服务器项目记得要重新运行,而修改了前端文件只需要刷新页面即可,向外部服务器发起请求要保持你电脑联网,否则报500错误。
运行结果展示
over~~~你学到了吗?🐻
今天也是元(shen)气(xin)满(ju)满(pi)的一天 ☁️
😜