尚硅谷视频:=95
axios官网教程:
vue配置代理:
安装axios发送ajax请求:
npm install axios
使用:(官网:)
也就是:
官网:
新建package.json
放在同级目录下),配置如下内容:
const { defineConfig } = require('@vue/cli-service')
ports = defineConfig({devServer: {proxy: 'localhost:5000'}
})
表示访问代理服务器,代理服务器就会帮你访问:localhost:5000
这样,就相当于配置了一个代理服务器,它和我们的项目具有相同的端口,我们访问它,就不存在跨域问题!
现在,我们访问代理服务器(端口为8080),而不是直接访问5000端口的服务器
总结一下,就是:
方式二的扩展性更好,原理和方法一是一样的!
新建package.json
放在同级目录下),配置如下内容:(含义在本文后面的总结里面有)
const { defineConfig } = require('@vue/cli-service')
ports = defineConfig({devServer: {proxy: {'/api': {target: 'localhost:5000',pathRewrite:{'^/api':''},//路径改写},}}
})
再修改一下路径:
const { defineConfig } = require('@vue/cli-service')
ports = defineConfig({devServer: {proxy: {'/api': {target: 'localhost:5000',pathRewrite:{'^/api':''},//路径改写},}}
})
import Vue from 'vue';
import App from './App.vue';new Vue({el: '#app',render: (h) => h(App),
});
<template><button @click="getStudentInfo">获取学生信息</button>
</template><script>
import axios from "axios"
export default {methods: {getStudentInfo() {('localhost:8080/api/student/1').then(function (response) {// handle successconsole.log(response);}).catch(function (error) {// handle errorconsole.log(error);}).then(function () {// always executed});}}
}
</script>
效果:
本文发布于:2024-01-29 07:32:11,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170648473313698.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |