在我們的項目,如何來通過前後端進行通信呢。下來我們分別介紹幾種方法。
1.reqwest方式
reqwest簡介
It's AJAX All over again. Includes support for xmlHttpRequest, JSONP, CORS, and CommonJS Promises A.
reqwest的寫法的ajax寫法類似,看下面例子
// 普通請求
reqwest({
url: 'path/to/json'
, type: 'json'
, method: 'post'
, data: { foo: 'bar', baz: 100 } // 入參
, error: function (err) { }
, success: function (resp) {
qwery('#content').html(resp.content)
}
})
// jsonp請求
reqwest({
url: 'path/to/json'
, type: 'jsonp'
, method: 'get' // jsonp請求,method可不寫,寫成post,依然會被瀏覽器默認爲get
, error: function (err) { }
, success: function (resp) {
qwery('#content').html(resp.content)
}
})
// cors請求
reqwest({
url: 'path/to/json'
, type: 'json'
, method: 'post'
, contentType: 'application/x-www-form-urlencoded'
, crossOrigin: true // cors跨域,服務端與客戶端存在cookie等數據憑證交互時需要設置crossOrigin,withCredentials
, withCredentials: true
, error: function (err) { }
, success: function (resp) {
qwery('#content').html(resp.content)
}
})
// promise寫法
reqwest({
url: 'path/to/data.jsonp?foo=bar'
, type: 'jsonp'
, jsonpCallback: 'foo'
})
.then(function (resp) {
qwery('#content').html(resp.content)
}, function (err, msg) {
qwery('#errors').html(msg)
})
.always(function (resp) {
qwery('#hide-this').hide()
})
下來看看在項目中的使用,來看一個get請求
首先封裝一個connection.js
import reqwest from 'reqwest'
import Cookies from 'js-cookie'
class Connection {
constructor(url, headers) {
this._url = url;
this._headers = headers;
}
requestGet() {
let url = this._url;
if(!_url) {
return Promise.reject(null);
}
let _headers = this._headers
let token = Cookies.get('access_token')
if(token) {
if(!_headers) {
_headers = {};
}
_headers.Authorization = 'Bearer ' + token;
}
return new Promise(function(resolve, reject) {
reqwest({
url: _url,
type: 'json',
method: 'GET',
headers: _headers,
success: resolve,
error: reject
})
})
}
}
export default Connection
request.js
import Connection from './connection.js';
import API from '../properties/api.js';
class Request {
static getUserInfos(subjectId, success, failure) {
const conn = new Connection(API.GetWorkFlowStatusAndNextActivities + '?subjectId=' + subjectId);
conn.requestGet().then(success, failure);
}
}
export default Request;
如何使用
Request.getUserInfos(subjectId,(data)=>{
console.log(data);
},(err)=>{
console.log(err)
})
2.axios方式
看一下axios的基本使用
下來看看在項目中具體是怎麼用的
request.js
import axios from 'axios';
import { getToken } from '@utils/auth';
const service = axios.create({
baseURL: process.env.BASE_API,
timeout: 150000
});
// request攔截器
service.interceptors.request.use(config => {
if (getToken()) {
config.headers.Authorization = 'Bearer ' + getToken();
}
return config;
}, error => {
console.error(error);
Promise.reject(error);
});
service.interceptors.response.use(
response => {
const res = response.data;
if (res && res.er.Message === 'Success') {
return res;
} else {
console.error(res.erMessage);
}
},
error => {
console.error(error);
Promise.reject(error);
}
);
export default service;
project.js
import request from '@/utils/request';
const workflowServiceHost = 'http://snbimsit.cnsuning.com/wf-snxd';
export function getDrawingInfo(param) {
return request({
url: `${workflowServiceHost}/api/WorkFlow/Project/GetItemInfoByWorkflowId`,
method: 'get',
params: params
})
}
使用
import { getDrawingInfo } from '@/api/project';
getDrawingInfo({ workflowId: this.workflowId }).then(res => {
if (res.items && res.items.Item) {
const obj = res.items.Item;
Object.keys(this.dialogData).forEach(key => {
this.dialogData[key] = obj[key];
});
}
});
3.ajax方式
jtl.util.Request.getData = function(url, options) {
options = options || {};
options.dataType = options.dataType || 'json';
var cache = options.cache || true;
url = jtl.util.Url.toHttps(url);
return new Promise(function(resolve, reject) {
var params = {
cache: cache,
url: url,
type: 'GET',
success: function(data) {
resolve(data);
},
error: function(ex) {
jtl.util.Common.error('getData error, url: ' + url, ex);
reject(ex);
}
};
Object.assign(params, options);
$.ajax(params);
});
};
使用
jtl.util.Request.getData(url).then(data => {
this.data = data;
});