axios在vue中的使用

  • axios在vue中的使用已关闭评论
  • 176 次浏览
  • A+
所属分类:Web前端
摘要

在该项目的vscode命令行下载npm i axios  在使用axios时涉及跨域问题你的8080窗口虽然发了请求,服务器也返回了消息,但是你收不到

在该项目的vscode命令行下载

npm i axios

axios在vue中的使用

 

 在使用axios时涉及跨域问题

你的8080窗口虽然发了请求,服务器也返回了消息,但是你收不到

1.cors 方式-----服务器给你返回响应时加特殊的响应头

2.jsonp方式 借助了 script 标签里面的src属性 引入外部资源时,不受同源策略限制办到的 只能解决get请求的跨域问题

3.代理服务器方式

axios在vue中的使用

 

 4.利用vue-cli脚手架解决跨域问题

方式一

这种方式不能设置多个代理,只能配置一个代理,而且不能灵活控制要不要走代理

在vue.config.js里面进行全局配置,写好端口号就行了,不用写具体路径了

//开启代理服务器
  devServer: {
    proxy:'http://localhost:5000'
  }
App.vue中
发起get请求时直接填8080窗口
<template>
  <div>
    <button @click="getStudents">捕获</button>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "App",
  methods: {
    getStudents() {
//http://localhost:8080/students这里代表着代理服务器的地址加上具体路径访问数据
      axios.get("http://localhost:8080/students").then(
        (response) => {
          console.log("请求成功", response.data);
        },
        (error) => {
          console.log("请求失败", error.message);
        }
      );
    },
  },
};
</script>

 如果在public里面有students,那么就不用走代理,直接拿资源
axios在vue中的使用

 

而不是去服务端的 students路径取值

方式二

vue.config.js:

 devServer: {
    proxy: {
      '/atguigu': {
        target: 'http://localhost:5000',
       
       
      }
    }
  }
App.vue:

axios.get("http://localhost:8080/atguigu/students").then(
        (response) => {
          console.log("请求成功", response.data);
        },
        (error) => {
          console.log("请求失败", error.message);
        }
      );
axios在vue中的使用

 

 

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  //方式二
  devServer: {
    proxy: {
      '/atguigu': {
        target: 'http://localhost:5000',
        pathRewrite: {'^/atguigu': ''}  //将匹配所有以atguigu开头的路径,将atguigu变成空字符串
       ws:true,//websocket用于支持websocket
  changeOrigin:false//说谎是否来自原客户端端口号
      }
    }
  }
})

 5.vue-resource
vue插件库
下载
npm i vue-resource
使用只要把axios替换成this.$http.get()就行了