forked from xxxXXX95/yuyue
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequest.js
64 lines (61 loc) · 1.69 KB
/
request.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const tough = require('tough-cookie');
const Cookie = tough.Cookie;
const fetch = require('node-fetch');
class Request {
constructor() {
this.cookiejar = new tough.CookieJar();
// this.Cookie = Cookie
this.tough = tough;
}
getCookies = url => {
return new Promise((resove, reject) => {
this.cookiejar.getCookies(url, (err, cookies) => {
if (err) reject(err);
resove(cookies);
});
});
};
setCookie = (url, cookie) => {
return new Promise((resove, reject) => {
this.cookiejar.setCookie(cookie, url, (err, cookie) => {
if (err) reject(err);
resove(cookie);
});
});
};
parse = (cookie, options) => {
return Cookie.parse(cookie, options);
};
request = async (url, preParams = {}, ignoreCookie = false) => {
const { headers = {} } = preParams;
// const getCookies = util.promisify(this.cookiejar.getCookies)
// const setCookie = util.promisify(this.cookiejar.setCookie)
// new Promise()
const cookies = await this.getCookies(url);
const params = {
...preParams,
headers: {
'content-type': 'application/x-www-form-urlencoded',
// 'Content-Type': 'application/json',
// redirect: 'manue',
...headers,
cookie: cookies.join(';')
}
};
return fetch(url, params)
.then(res => {
if(ignoreCookie) return res
const cookies = res.headers.raw()['set-cookie'];
if (cookies) {
cookies.map(Cookie.parse).forEach(cookie => {
this.setCookie(url, cookie);
});
}
return res;
})
.catch(e => {
console.log('请求出错url:', url);
});
};
}
module.exports = Request;