TA的每日心情 | 开心 2021-12-13 21:45 |
---|
签到天数: 15 天 [LV.4]偶尔看看III
|
1.安装
或者 使用 bower:
或者直接使用 cdn:
- <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
复制代码
2.引入axios
- import axios from "axios"
复制代码
这时候如果在其它的组件中,是无法使用 axios 命令的。但如果将 axios 改写为 vue 的原型属性,就能解决这个问题
- Vue.prototype.axios = axios
复制代码
通过 this.axios({})来访问
3.基本使用
- axios({
- url:"http://localhost/api/aaa",
- method:"POST",
- headers:{
- Authorization:"Bearer eyJ0eXAiABUg-Fxs...",
- Accept:"application/json"
- }
- }).then(res=>{
- console.log(res,"res")
- }).catch(res1=>{
- console.log(res1,"res1")
- })
复制代码
然后报CORS错误
Access to XMLHttpRequest at "http://backend.com/api/aaa" from origin "http://localhost:8085" has been blocked by CORS policy: Response to preflight request doesn"t pass access control check: No "Access-Control-Allow-Origin" header is present on the requested resource.
根据提示可以看出是跨越了
跨越的三个条件:协议、域名、端口号
这个请求明显端口号不一致,找到问题了,那就好说了
4.axios配置 proxyTable
在config/index.js中的proxyTable中添加以下内容:
- "/api": {
- target: "http://backend.com/api",
- changeOrigin: true,
- pathRewrite: {
- "^/api": ""
- }
- }
复制代码
保存,重新运行 npm run dev
5.更改url,重新请求
- axios({
- url:"/api/aaa",
- method:"POST",
- headers:{
- Authorization:"Bearer 5llcq3GiwABUg-Fxs...",
- Accept:"application/json"
- }
- }).then(res=>{
- console.log(res,"res")
- }).catch(res1=>{
- console.log(res1,"res1")
- })
复制代码
请求结果如下,跨越解决了
|
|