vue中的网络请求

参考网址:

  1. javascript - Uncaught TypeError: Cannot read property 'get' of undefined in VueJs - Stack Overflow
  2. Ajax、fetch、axios · 要努力 · 看云 (kancloud.cn)
  3. https://blog.csdn.net/m0_57836225/article/details/140580939
  4. https://www.jb51.net/article/273433.htm
  5. https://blog.csdn.net/ljf12138/article/details/103100536

 vue发送网络请求有以下几种方式:

  1. 传统的Ajax方式时基于XMLHttpRequest(XHR),调用层级过多会出现回调地狱
  2. jQuery-Ajax,时对原生Ajax的封装,太笨重,使用代码为 $.ajax  $.get  $.post 
  3. Vue-resource,时vue1.0时使用,需要下载安装VueResource,使用代码为 $http.get()
  4. axios【最常用】,本质也是对原生XHR的封装,是它的Promise实现版本

$ 在vue中表示全局变量或方法,如 $el  $data  $watch  $refs  $route

但某些第三方库也会用$定义自己的属性和方法,如jquery :   import $ from 'jquery' 


vue2中使用axios

  1. 安装: npm i axios
  2. 导入:可以在main.js配置,也可以在使用的单页面直接 import
  3. 使用:this.axios.get()

全局引入

main.js

import axios from "axios";

//挂载到 vue.prototype时有没有 $ 均可
Vue.prototype.axios = axios;

使用: App.vue

this.axios.get(url).then(res => {
    console.log('res', res.data);
}).catch(err => {
    console.log('err', err);
})

非全局引入+使用

App.vue

import axios from 'axios';

axios.get(url).then(res => {
    console.log('res', res.data);
}).catch(err => {
    console.log('err', err);
})

跨域怎么办

目前可用的一个测试网址是 https://jsonplaceholder.typicode.com/posts/1 ,原先的网址失效了。同时可以自己用IDEA或者node.js搭一个服务器,用本地网址类似 http://localhost:8081/all 测试。

如果暂时不想处理跨域问题,可以在Chrome装一个插件:Allow CORS: Access-Control-Allow-Origin 

安装以后点一下,左下角有一个 ON|OFF,点一下ON,插件图标变成彩色就可以屏蔽跨域了。

 

同时可以点击 Test CORS 测试跨域是否被屏蔽。

 

posted @ 2024-07-31 16:46  sunshine233  阅读(3)  评论(0编辑  收藏  举报