VUE中如何發(fā)ajax請求

vue中是推薦使用axios來發(fā)送請求的。而且在vue2.0之后也是使用axios來實現發(fā)送ajax請求的。

1. 安裝

axios有好幾種引用的方式,其中主要包括如下:

  • 使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  • 使用npm

$ npm install axios

  • 使用 bower:

$ bower install axios

使用

1.get請求

   mounted: function() {
      axios
          .get('http://www.mycart.com:7772/allItems')
          .then(response => (
          this.items = response.data))
          .catch(function (error) { // 請求失敗處理
            console.log(error);
          });
      }

帶有參數的形式

// 直接在 URL 上添加參數 ID=12345
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 
// 也可以通過 params 設置參數:
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

2. post請求

let formData = new FormData();
        //下面是表單綁定的data 數據
        formData.append('skuId', item.skuId);
        formData.append('quantity',1);      
        axios
        .post("http://www.mycart.com:7771/cart",formData)
        .then(resp=>{
            alert("商品添加購物車成功!");
        })
        .catch(function (error) { // 請求失敗處理
        alert("商品添加購物車失敗");         
      });

也可以這樣傳遞參數

axios.post('/user', {
    firstName: 'Fred',        // 參數 firstName
    lastName: 'Flintstone'    // 參數 lastName
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

跨域請求

axios 默認是不能進行跨域請求的,而且也沒法攜帶cookie,在vue中需要進行如下配置:

 axios.defaults.withCredentials = true;
 axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
 axios.defaults.crossDomain = true;

然后后端也要進行跨域的設置,比如使用@Crossorigin注解,但是需要注意的是允許訪問的域名不能使用通配符*,否則會失效。下面給出后端配置的代碼樣例:

@CrossOrigin(origins= {"http://www.mycart.com"}, allowCredentials = "true")
public class ItemController {
......
}
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容