当前位置:   article > 正文

vue使用axios解决跨域get和post请求

vue使用axios解决跨域get和post请求

step1: 跨域插件

插件地址:https://github.com/deraw/vue-cli-plugin-proxy

yarn add @deraw/vue-cli-plugin-proxy
  • 1

C:\Users\Windows\WebstormProjects\untitled\vue.config.js

 // vue.config.js
module.exports = {
  devServer: {
    port: 8081,
    proxy: {
      // '/other/path' don't be included in 'pluginOptions.proxy.context'.
      '/other/path': {
        target: 'http://192.168.0.188:5000',
        changeOrigin: true
      },
    },
  },
  pluginOptions: {
    proxy: {
      enabled: true,
      context: ['/api', '/oauth2', '/login', '/auth/conf'],
      options: {
        target: 'http://192.168.0.188:5000',
        secure: false,
        headers: {
          host: 'localhost:8081',
        },
      },
    },
  },
};

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

step2: 安装axios 网络请求框架

插件地址:https://www.npmjs.com/package/vue-axios?activeTab=readme

yarn add --save axios vue-axios 
  • 1

step3:package.json版本号

  "dependencies": {
    "@deraw/vue-cli-plugin-proxy": "^2.2.7",
    "axios": "^1.6.8",
    "core-js": "^3.8.3",
    "vue": "^3.2.13",
    "vue-axios": "^3.5.2"
  },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

step4:引用axios

import App from './App.vue'
import * as Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

const app = Vue.createApp(App)
app.use(VueAxios, axios)
app.mount('#app')

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

step5: 主界面,调用axios 使用get post请求

<template>
  <span><a @click="register()">去注册</a></span>
  <span><a @click="postData()">去登录</a></span>
</template>

<script>


export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  methods: {
    register() {
      this.axios.get('/api/queryall').then((response) => {
        console.log(response)
      })
    },
    async postData() {
      const data = {
        id: 4,
        lastName: 'ffsssaaaaassf',
        email: '5207694232@qq.com'
      };
      this.axios.post('/api/adds', data).then(function (response) {
        console.log(response);
      }).catch(function (error) {
        console.log(error);
      });
    },
  }
}
</script>
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

打开浏览器,运行,会发现,成功解决跨域问题

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/542565
推荐阅读
相关标签
  

闽ICP备14008679号