赞
踩
step1: 跨域插件
插件地址:https://github.com/deraw/vue-cli-plugin-proxy
yarn add @deraw/vue-cli-plugin-proxy
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', }, }, }, }, };
step2: 安装axios 网络请求框架
插件地址:https://www.npmjs.com/package/vue-axios?activeTab=readme
yarn add --save axios vue-axios
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"
},
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')
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>
打开浏览器,运行,会发现,成功解决跨域问题,
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。