【vue】使用axios发送哀求

打印 上一主题 下一主题

主题 1016|帖子 1016|积分 3048




  
一、项目环境设置

根组件App.vue

路由设置

main.js设置
固定写法,复制粘贴即可

二、使用axios发送POST哀求登录

  1. <template>
  2.         <div class="box1">
  3.                 <el-form label-width="120px">
  4.                         <el-form-item label="用户名">
  5.                                 <el-input v-model="loginForm.username"></el-input>
  6.                         </el-form-item>
  7.                         <el-form-item label="密码">
  8.                                 <el-input type="password" v-model="loginForm.password"></el-input>
  9.                         </el-form-item>
  10.                         <el-form-item>
  11.                                 <el-button style="width:100%" type="primary" @click="submitLogin">登录</el-button>
  12.                         </el-form-item>
  13.                 </el-form>
  14.         </div>
  15. </template>
  16. <script>
  17. import axios from 'axios'
  18.         // 使用axios发送post请求
  19.         // 案例:实现登录
  20.         export default{
  21.                 data(){
  22.                         return{
  23.                                 loginForm:{
  24.                                         username:"",
  25.                                         password:""
  26.                                 }
  27.                         }
  28.                 },
  29.                 methods:{
  30.                         // 点击登录执行的方法
  31.                         submitLogin(){
  32.                                 console.log('点击了登录,',this.loginForm)
  33.                                 // 点击了登录如何发送http请求?axios
  34.                                 const params={
  35.                                         username:this.loginForm.username,
  36.                                         password:this.loginForm.password
  37.                                 }
  38.                                 // 登录的post请求
  39.                                 const res = axios.post('http://82.156.178.247:5001/users/login/',params)
  40.                                 console.log('res',res)
  41.                                 // 设置回调函数,接收返回的响应对象
  42.                                 // 异步操作成功时,执行的回调函数
  43.                                 res.then(response=>{
  44.                                         console.log('请求成功:')
  45.                                         console.log('respnse',response)
  46.                                 })
  47.                                 // 异步操作失败时,执行的回调函数
  48.                                 res.catch(error=>{
  49.                                         console.log('请求失败:')
  50.                                         // console.log('error:',error)
  51.                                         console.log('请求失败响应对象获取',error.response)
  52.                                 })
  53.                         }
  54.                 }
  55.         }
  56. </script>
  57. <style>
  58. </style>
复制代码
哀求失败时,控制台输出的对象

哀求成功时,控制台输出的对象

三、异步实现:使用axios发送POST哀求登录(json)

  1. <template>
  2.         <div class="box1">
  3.                 <el-form label-width="120px">
  4.                         <el-form-item label="用户名">
  5.                                 <el-input v-model="loginForm.username"></el-input>
  6.                         </el-form-item>
  7.                         <el-form-item label="密码">
  8.                                 <el-input type="password" v-model="loginForm.password"></el-input>
  9.                         </el-form-item>
  10.                         <el-form-item>
  11.                                 <el-button style="width:100%" type="primary" @click="submitLogin">登录</el-button>
  12.                         </el-form-item>
  13.                 </el-form>
  14.         </div>
  15. </template>
  16. <script>
  17. import axios from 'axios'
  18.         // 使用axios发送post请求
  19.         // 案例:实现登录
  20.         export default{
  21.                 data(){
  22.                         return{
  23.                                 loginForm:{
  24.                                         username:"",
  25.                                         password:""
  26.                                 }
  27.                         }
  28.                 },
  29.                 methods:{
  30.                         // 点击登录执行的方法
  31.                         async submitLogin(){
  32.                                 const params={
  33.                                         username:this.loginForm.username,
  34.                                         password:this.loginForm.password
  35.                                 }
  36.                                 // 登录的post请求
  37.                                 const response =await axios.post('http://82.156.178.247:5001/users/login/',params)
  38.                                 console.log('response:',response)
  39.                                 // 对响应信息进行判断
  40.                                 if (response.status===200){
  41.                                         this.$message({
  42.                                                 type:"success",
  43.                                                 message:"登录成功"
  44.                                         });
  45.                                         // 跳转
  46.                                         this.$router.push({name:"index"})
  47.                                 }
  48.                         },
  49.                 }
  50.         }
  51. </script>
  52. <style>
  53. </style>
复制代码
四、异步实现:使用axios发送POST哀求登录(表单)


  1. <template>
  2.         <div class="box1">
  3.                 <el-form label-width="120px">
  4.                         <el-form-item label="用户名">
  5.                                 <el-input v-model="loginForm.username"></el-input>
  6.                         </el-form-item>
  7.                         <el-form-item label="密码">
  8.                                 <el-input type="password" v-model="loginForm.password"></el-input>
  9.                         </el-form-item>
  10.                         <el-form-item>
  11.                                 <el-button style="width:100%" type="primary" @click="submitLogin">登录</el-button>
  12.                         </el-form-item>
  13.                 </el-form>
  14.         </div>
  15. </template>
  16. <script>
  17. import axios from 'axios'
  18. import qs from 'qs'
  19.         // 使用axios发送post请求
  20.         // 案例:实现登录
  21.         export default{
  22.                 data(){
  23.                         return{
  24.                                 loginForm:{
  25.                                         username:"",
  26.                                         password:""
  27.                                 }
  28.                         }
  29.                 },
  30.                 methods:{
  31.                         // 点击登录执行的方法
  32.                         async submitLogin(){
  33.                                 // axios发送表单格式的请求
  34.                                 const params = qs.stringify(this.loginForm)
  35.                                 // 登录的post请求
  36.                                 const response =await axios.post('http://82.156.178.247:5001/users/login/',params)
  37.                                 console.log('response:',response)
  38.                                 // 对响应信息进行判断
  39.                                 if (response.status===200){
  40.                                         this.$message({
  41.                                                 type:"success",
  42.                                                 message:"登录成功"
  43.                                         });
  44.                                         // 跳转
  45.                                         this.$router.push({name:"index"})
  46.                                 }
  47.                         },
  48.                 }
  49.         }
  50. </script>
  51. <style>
  52. </style>
复制代码
五、token存储

生存登录返回的token
获取token
const token=response.data.token
生存到LocalStorage中:永久存储,只有不手动删除,永久生存到LocalStorage中
window.localStorage.setItem(‘token’,token)
生存到sessionStorage中:关闭浏览器之后,删除内容
window.sessionStorage.setItem(‘token’,token)
生存到cookie中:
window.cookieStore.set(‘token’,token)

  1. <template>
  2.         <div class="box1">
  3.                 <el-form label-width="120px">
  4.                         <el-form-item label="用户名">
  5.                                 <el-input v-model="loginForm.username"></el-input>
  6.                         </el-form-item>
  7.                         <el-form-item label="密码">
  8.                                 <el-input type="password" v-model="loginForm.password"></el-input>
  9.                         </el-form-item>
  10.                         <el-form-item>
  11.                                 <el-button style="width:100%" type="primary" @click="submitLogin">登录</el-button>
  12.                         </el-form-item>
  13.                 </el-form>
  14.         </div>
  15. </template>
  16. <script>
  17. import axios from 'axios'
  18. import qs from 'qs'
  19.         // 使用axios发送post请求
  20.         // 案例:实现登录
  21.         export default{
  22.                 data(){
  23.                         return{
  24.                                 loginForm:{
  25.                                         username:"",
  26.                                         password:""
  27.                                 }
  28.                         }
  29.                 },
  30.                 methods:{
  31.                         // 点击登录执行的方法
  32.                         async submitLogin(){
  33.                                 // axios发送json格式的请求
  34.                                 const params={
  35.                                         username:this.loginForm.username,
  36.                                         password:this.loginForm.password
  37.                                 }
  38.                                 // 登录的post请求
  39.                                 const response =await axios.post('http://82.156.178.247:5001/users/login/',params)
  40.                                 console.log('response:',response)
  41.                                 // 对响应信息进行判断
  42.                                 if (response.status===200){
  43.                                         this.$message({
  44.                                                 type:"success",
  45.                                                 message:"登录成功"
  46.                                         });
  47.                                         // 跳转
  48.                                         this.$router.push({name:"index"})
  49.                                         // 保存登录返回的token
  50.                                         // 获取token
  51.                                         const token=response.data.token
  52.                                         // 保存到LocalStorage中
  53.                                         // window.localStorage.setItem('token',token)
  54.                                         // // 保存到sessionStorage中
  55.                                         // window.sessionStorage.setItem('token',token)
  56.                                         // 保存到cookie中
  57.                                         window.cookieStore.set('token',token)
  58.                                 }
  59.                         },
  60.                 }
  61.         }
  62. </script>
  63. <style>
  64. </style>
复制代码
六、token使用

  1. <template>
  2.         <h1>index页面</h1>
  3.         <el-button @click="getAllProject">获取项目数据</el-button>
  4.         <h3>{{pros}}</h3>
  5. </template>
  6. <script>
  7. import axios from 'axios'
  8.         export default{
  9.                 data(){
  10.                         return{
  11.                                 pros:{
  12.                                 }
  13.                         }
  14.                 },
  15.                 methods:{
  16.                         async getAllProject(){
  17.                                 // 发送请求
  18.                                 const url="http://82.156.178.247:5001/projects/"
  19.                                 const response=await axios.get(url,{
  20.                                         headers:{
  21.                                                 'Authorization':'JWT ' + window.sessionStorage.getItem('token')
  22.                                         }
  23.                                 });
  24.                                 console.log('response',response);
  25.                                 this.pros=response.data
  26.                         }
  27.                 }
  28.         }
  29. </script>
  30. <style>
  31. </style>
复制代码

七、全局的axios设置

在api/index.js中对axios对后端哀求举行同一封装

1、方式一

  1. // 针对axios对后端请求进行统一封装(方便后期维护管理)
  2. import axios from "axios"
  3. // 方式一:直接配置axios对象,进行相关的封装
  4. // 设置全局的baseURL
  5. axios.defaults.baseURL='http://82.156.178.247:5001'
  6. axios.defaults.headers.common['kobe']='0924'
  7. export const login=(params)=>{
  8.         axios.post('/login',params)
  9. }
  10. export const getALLPro=()=>{
  11.         axios.get('/login')
  12. }
复制代码
2、方式二

  1. // 方式二:使用axios创建实例进行相关的配置和封装(适用于微服务的架构)
  2. const http=axios.create({
  3.         // 配置baseURL
  4.         baseURL:'http://82.156.178.247:5001',
  5.         // 配置请求成功的http响应状态码的范围(全部当作成功的处理)
  6.         validateStatus:function(status){
  7.                 return true;
  8.         }
  9. })
  10. export default{
  11.         login(params){
  12.                 return http.post('/login/',params)
  13.         },
  14.         getAllProject(){
  15.                 return http.get('/projects/')
  16.                        
  17. }
  18. }
复制代码
在main.js中导入index.js,作为全局对象,方便以后的开辟项目中使用
$api为属性名称

八、哀求拦截器和响应拦截器

  1. // 设置请求拦截器
  2. http.interceptors.request.use(function (config){
  3.         // config为请求对象
  4.         // 如果不是登录接口,那么在请求头中加上Authorization
  5.         if(config.url!=='/login/'){
  6.                 config.headers['Authorization']='JWT ' + window.sessionStorage.getItem('token')
  7.         }
  8.         // 每个请求发送之前都会执行该方法,并且会将请求配置对象传到该方法中
  9.         console.log('请求拦截器:',config)
  10.        
  11.         // 在发送请求之前
  12.         return config
  13. });
  14. // 响应拦截器:每个接口请求
  15. http.interceptors.response.use(function(response){
  16.         // 对响应数据做点什么
  17.         console.log('响应拦截器:',response)
  18.         // 在此处对项目中接口调用失败,做统一处理
  19.         return response;
  20.        
  21. })
复制代码



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

熊熊出没

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表