7、Vue http

一、vue-resource

1、vue-resource簡介

vue-resource是Vue的一個http插件,功能類似於ajax。

可以通過使用全局Vue.http或者Vue實例this.$http來引用http服務。

官網地址:https://github.com/vuejs/vue-resource

2、安裝vue-resource

在package.json中引入vue-resource,然後使用npm install安裝
“dependencies”: {
“vue”: “^2.5.2”,
“vue-resource”: “^1.5.1”
}

vue-resource安裝

npm install
// 或者
cnpm install

在src/main.js中使用插件

import VueResource from 'vue-resource'
Vue.use(VueResource)
3、請求方式

常用的有get、post、put、delete,每個函數的返回值都是Promise對象,異步API請求成功後會調用then()方法

// 獲取資源
Promise get(url, [options])
// 創建資源
Promise post(url, [body], [options])
// 修改資源
Promise put(url, [body], [options])
// 刪除資源
Promise delete(url, [options])

Promise head(url, [options])
Promise jsonp(url, [options])
Promise patch(url, [body], [options])


// 全局Vue對象
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

// Vue實例
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

使用示例

this.$http.get('/someUrl').then((response) => {
  // success callback
}, (response) => {
  // error callback
});
請求
參數 類型 描述
url string 請求發送到的 URL
body Object, FormData, string 請求中要發送的數據
headers Object 作爲 HTTP 請求頭髮送的 Headers 對象
params Object 作爲 URL 參數發送的 Parameters 對象
method string HTTP 方法 (例如: GET, POST, …)
timeout number 請求超時的毫秒數 (0 爲不超時)
before function(request) 在請求發送之前用於修改請求選項的回調函數
progress function(event) 上傳時用於控制 ProgressEvent 的回調函數
credentials boolean Indicates whether or not cross-site Access-Control requests should be made using credentials
emulateHTTP boolean 如果Web服務器無法處理PUT, PATCH和DELETE這種REST風格的請求,你可以啓用enulateHTTP現象。啓用該選項後,請求會以普通的POST方法發出,並且HTTP頭信息的X-HTTP-Method-Override屬性會設置爲實際的HTTP方法。 Vue.http.options.emulateHTTP = true;
emulateJSON boolean 如果Web服務器無法處理編碼爲application/json的請求,你可以啓用emulateJSON選項。啓用該選項後,請求會以application/x-www-form-urlencoded作爲MIME type,就像普通的HTML表單一樣。 Vue.http.options.emulateJSON = true;
響應
屬性 類型 描述
url string 響應的源 URL
body Object, Blob, string 響應的數據報文
headers Header 響應頭對象
ok boolean 從 200 到 299 的 HTTP 狀態碼
status number 響應中的 HTTP 狀態碼
statusText string 響應中的 HTTP 狀態文本
函數 類型 描述
text() Promise 作爲字符串解析報文
json() Promise 作爲 Json 對象解析報文
blob() Promise 作爲 Blob 對象解析報文
4、簡單示例

App.vue

<template>
  <div id="app">
    {{ res }}
  </div>
</template>

<script>
  export default {
    name: 'App',
    data () {
      return {
        res: {}
      }
    },
    created () {
      this.$http.post('http://127.0.0.1:9000/api/user/login',
        {username: 'mengday', password: '123456'},
        {emulateJSON:true})
        .then((response) => {
          let body = response.body
          this.res = body
        }, (error) => {
          console.log(error)
        })
        .catch(error => {
          console.log('在整個請求到響應過程中,只要程序出錯了就會被調用。')
        }
      )
    }
  }
</script>

catch方法用於捕捉程序的異常,catch方法和errorCallback是不同的,errorCallback只在響應失敗時調用,而catch則是在整個請求到響應過程中,只要程序出錯了就會被調用。

interceptors:攔截器用於攔截請求,可以在請求發送前做一些操作(如對數據進行簽名、顯示加載中、修改請求方式、修改請求參數等),也可以在請求響應後做一些處理(如驗證請求報文等,驗證接口的錯誤碼等)。

src/main.js

// 全局請求攔截器
Vue.http.interceptors.push((request, next) => {
  console.log('前置攔截:在請求前攔截, 例如修改請求, 顯示loading')
  console.log(request.body)
  request.headers.set('AccessToken', 'token')
  next((response) => {
    console.log('後置攔截:在請求響應後攔截, 例如驗籤等')
    console.log(response.body)
  })
})

注意:在接口調用時會出現跨域問題,可以放在後端解決,也可以使用jsonp()來解決。

@Configuration
@EnableWebMvc
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowCredentials(false).maxAge(3600);
    }
}



SampleController
@RestController
@RequestMapping("/api/user")
public class SampleController {

    @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        @RequestHeader("AccessToken") String token) {
        String result = "{" +
                "\"code\": 0," +
                "\"msg\": \"SUCCESS\"," +
                "\"data\": {" +
                "\"username\": \"" + username + "\"," +
                "\"token\":\"" + UUID.randomUUID() + "\"" +
                "}" +
                "}";

        return result;
    }
}

二、axios

1、簡介

vue2.0之後,就不再對vue-resource更新,而是推薦使用axios。基於 Promise 的 HTTP 請求客戶端,可同時在瀏覽器和 Node.js 中使用。

// 安裝axios  
// --save 是將插件名稱和版本號添加到package.json中的dependencies中
cnpm install --save axios
或
npm install --save axios

在src/main.js中引入axios

import axios from 'axios'
2、api
Promise axios.request(config)
Promise axios.get(url [,config])
Promise axios.post(url [,data [,config]])
Promise axios.put(url [,data [,config]])
Promise axios.delete(url [,config])
Promise axios.head(url [,config])
Promise axios.patch(url [,data [,config]]// 構造函數:根據配置選項創建一個Axios實例對象
AxiosInstance axios.create([config])

config
{
	// `url`是將用於請求的服務器URL
	url: '/user',
	
	// `baseURL`將被添加到`url`前面,除非`url`是絕對的。
	// 可以方便地爲 axios 的實例設置`baseURL`,以便將相對 URL 傳遞給該實例的方法。
	baseURL: 'https://some-domain.com/api/',
	
	// `method`是發出請求時使用的請求方法
	method: 'get', // 默認
	
	// “responseType”表示服務器將響應的數據類型
	responseType: 'json', // default
	
	// `headers`是要發送的自定義 headers
	headers: {'Content-Type': 'application/json'},
	
	// `params`是要與請求一起發送的URL參數
	// 必須是純對象或URLSearchParams對象
	params: {
	    ID: 12345
	},

	// `paramsSerializer`是一個可選的函數,負責序列化`params`
	// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
	paramsSerializer: function(params) {
	    return Qs.stringify(params, {arrayFormat: 'brackets'})
	},
	
	// `data`是要作爲請求主體發送的數據
	// 僅適用於請求方法“PUT”,“POST”和“PATCH”
	// 當沒有設置`transformRequest`時,必須是以下類型之一:
	// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
	// - Browser only: FormData, File, Blob
	// - Node only: Stream
	data: {
	  firstName: 'Fred'
	},
	
	// `timeout`指定請求超時之前的毫秒數。
	// 如果請求的時間超過'timeout',請求將被中止。
	timeout: 1000,
	
	// `transformRequest`允許在請求數據發送到服務器之前對其進行更改
	// 這隻適用於請求方法'PUT','POST'和'PATCH'
	// 數組中的最後一個函數必須返回一個字符串,一個 ArrayBuffer或一個 Stream
	transformRequest: [function (data) {
	  // 做任何你想要的數據轉換
	
	  return data;
	}],
	
	// `transformResponse`允許在 then / catch之前對響應數據進行更改
	transformResponse: function (data) {
	// Do whatever you want to transform the data
	
	  return data;
	}],
	
	
	// `withCredentials`指示是否跨站點訪問控制請求
	// should be made using credentials
	withCredentials: false, // default
	
	// `adapter'允許自定義處理請求,這使得測試更容易。
	// 返回一個promise並提供一個有效的響應(參見[response docs](#response-api))
	adapter: function (config) {
	
	},
	
	// `auth'表示應該使用 HTTP 基本認證,並提供憑據。
	// 這將設置一個`Authorization'頭,覆蓋任何現有的`Authorization'自定義頭,使用`headers`設置。
	auth: {
	  username: 'xxx',
	  password: 'xxx'
	},
	
	//`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名稱
	xsrfCookieName: 'XSRF-TOKEN', // default
	
	// `xsrfHeaderName`是攜帶xsrf令牌值的http頭的名稱
	xsrfHeaderName: 'X-XSRF-TOKEN', // default
	
	// `onUploadProgress`允許處理上傳的進度事件
	onUploadProgress: function (progressEvent) {
	// 使用本地 progress 事件做任何你想要做的
	},
	
	// `onDownloadProgress`允許處理下載的進度事件
	onDownloadProgress: function (progressEvent) {
	// Do whatever you want with the native progress event
	},
	
	// `maxContentLength`定義允許的http響應內容的最大大小
	maxContentLength: 2000,
	
	// `validateStatus`定義是否解析或拒絕給定的promise
	// HTTP響應狀態碼。如果`validateStatus`返回`true`(或被設置爲`null` promise將被解析;否則,promise將被
	  // 拒絕。
	validateStatus: function (status) {
		return status >= 200 && status < 300; // default
	},
	
	// `maxRedirects`定義在node.js中要遵循的重定向的最大數量。
	// 如果設置爲0,則不會遵循重定向。
	maxRedirects: 5, // 默認
	
	// `httpAgent`和`httpsAgent`用於定義在node.js中分別執行http和https請求時使用的自定義代理。
	// 允許配置類似`keepAlive`的選項,
	// 默認情況下不啓用。
	httpAgent: new http.Agent({ keepAlive: true }),
	httpsAgent: new https.Agent({ keepAlive: true }),
	
	// 'proxy'定義代理服務器的主機名和端口
	// `auth`表示HTTP Basic auth應該用於連接到代理,並提供credentials。
	// 這將設置一個`Proxy-Authorization` header,覆蓋任何使用`headers`設置的現有的`Proxy-Authorization` 自定義 headers。
	proxy: {
	  host: '127.0.0.1',
	  port: 9000,
	  auth: : {
	  	username: 'xxx',
	    password: 'xxxx'
	  }
	},
	
	// “cancelToken”指定可用於取消請求的取消令牌
	// (see Cancellation section below for details)
	cancelToken: new CancelToken(function (cancel) {
	
	})
}
3、請求示例
// 自定義Axios實例
var instance = axios.create({
  method: 'POST',
  baseURL: 'https://api.example.com'
})
instance.defaults.headers.common ['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$http = instance

// axios(url[, config])
axios({
	method: 'post',
	url: '/user/12345',
	data: {
		firstName: 'Fred',
		lastName: 'Flintstone'
	}
});
4、簡單示例

src/main.js

import axios from 'axios'

// 給Vue實例添加一個是個屬性,這樣在每個實例中就可以使用this.$http來訪問axios實例了
Vue.prototype.$http = axios

// 一些默認的參數
axios.defaults.baseURL = 'http://127.0.0.1:9000/api'

// 請求攔截器:在發送請求前攔截
axios.interceptors.request.use(config => {
  console.log('請求發送前攔截')
  config.headers.common['AccessToken'] = 'token'
  return config;
}, error => {
  return Promise.reject(error)
})

// 響應攔截器:在請求響應之後攔截
axios.interceptors.response.use(response => {
  console.log('請求響應後處理')
  return response;
}, error => {
  return Promise.reject(error)
})

App.vue

<template>
  <div id="app">
    {{ res }}
  </div>
</template>

<script>
  export default {
    name: 'App',
    data () {
      return {
        res: {}
      }
    },
    created () {
      this.$http.post('/user/login',
        {username: "mengday", password: "123456"})
        .then(response => {
          console.log(response)
          if (response.data.code === 0) {
            this.res = response.data.data
          }
        })
        .catch(error => {
          console.log(error)
        })
    }
  }
</script>

SampleController

@RestController
@RequestMapping("/api/user")
public class SampleController {

    @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String login(@RequestBody User user) {
        String result = "{" +
                "\"code\": 0," +
                "\"msg\": \"SUCCESS\"," +
                "\"data\": {" +
                "\"username\": \"" + user.getUsername() + "\"," +
                "\"token\":\"" + UUID.randomUUID() + "\"" +
                "}" +
                "}";

        return result;
    }
}

三、mockjs

開發中前端開發和後端開發一般是同時開發的,不可能前端開發等後端接口開發好後再開發,只需要後端API給出接口定義即可,然後前端就可以模擬後臺API進行開發。

mockjs官網:https://github.com/nuysoft/Mock/wiki

1、安裝mockjs
nom install --save mockjs
或者
cnpm install --save mockjs
2、src/mock/index.js
import Mock from 'mockjs'
import { Random } from 'mockjs'

// 全局設置
Mock.setup({
  timeout: 1000
})

function success(data) {
  return {
    code: 0,
    msg: 'SUCCESS',
    data: data
  }
}

function error(code, msg) {
  return {
    code: code,
    msg: msg
  }
}

//模擬後臺返回的數據
let users = () => {
  let data = {
    guid: Random.guid(),
    string: Random.string(10),
    number: Random.string('number', 8, 10),
    date: Random.date('yyyy-MM-dd'),
    time: Random.time('A HH:mm:ss'),
    county: Random.county(),
    cword: Random.cword(4, 16), // 隨機生成任意名稱
    cname: Random.cname(),
    csentence: Random.csentence(10, 32)
  }

  return success(data)
}

// 路徑和方法綁定
// rtype表示需要攔截的 Ajax 請求類型。例如 GET、POST、PUT、DELETE 等
Mock.mock('/users', /GET|POST|PUT|DELETE/i, users)
3、src/main.js
import './mock/index.js'

// 注意mock時不支持baseURL
// axios.defaults.baseURL = 'http://127.0.0.1:9000/api'

3.4 App.vue
this.$http
	.post('/users')
    .then(response => {
      console.log(response)
      if (response.data.code === 0) {
        this.res = response.data.data
      }
    })
    .catch(error => {
      console.log(error)
    })
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章