36 lines
1.1 KiB
JavaScript
36 lines
1.1 KiB
JavaScript
/**
|
|
* example: <br>
|
|
* <p>GET=>request('http://localhost:3000/aricle/detail?id=1').then()... </p>
|
|
* <p>GET=>request('http://localhost:3000/aricle/detail',{id:1}).then()... </p>
|
|
* request('http://localhost:3000/aricle/detail',{id:1},'POST').then()... <br>
|
|
* @param {string} url
|
|
* @param {any} params
|
|
* @param {'GET'|'POST'} method
|
|
* @returns
|
|
*/
|
|
const request = (url, params = {}, method = 'GET') => {
|
|
return new Promise((resovle, reject) => {
|
|
const options = {
|
|
method: method
|
|
}
|
|
if (method.toUpperCase() == 'GET') {
|
|
const query = [];
|
|
for (let key in params) {
|
|
|
|
query.push(`${key}=` + params[key]);
|
|
}
|
|
url = url + (url.includes('?') ? "&" : "?") + query.join('&')
|
|
} else {
|
|
options.headers = {
|
|
'Content-Type': 'application/json'
|
|
}
|
|
options.body = JSON.stringify(params) // 对象转json
|
|
}
|
|
fetch(url, options)
|
|
.then(res => res.json())
|
|
.then(resovle)
|
|
.catch(e => reject(e))
|
|
});
|
|
}
|
|
//
|
|
export default request |