puppeteer+axios保持登录请求
安装
yarn add axios axios-cookiejar-support tough-cookie puppeteer
1
基本使用
import axios from 'axios';
import { wrapper } from 'axios-cookiejar-support';
import { CookieJar, Cookie } from 'tough-cookie';
const puppeteer = require('puppeteer');
const jar = new CookieJar();
const client = wrapper(axios.create({ jar }));
let userAgent = ''
// 启动浏览器
const browser = await puppeteer.launch({
headless: false
});
// 新建一个标签页
const pages = await browser.newPage();
// 监听请求
pages.on('request', req => {
console.log('请求头:', req.headers());
userAgent = req.headers()['user-agent']
});
// 前往地址
pages.goto('http://test.mrcdh.cn/api/index/sessionLogin')
// 从puppeteer中获取cookie
const cookies = await pages.cookies();
// 设置到axios中
cookies.forEach(json => {
const {name, domain} = json
json.key =name
json.expires = json.expires > 0 ? new Date(json.expires * 1000) : 'Infinity'
const cookie = Cookie.fromJSON(json)
jar.setCookie(cookie, 'http://' + domain)
});
// 请求就带cookie了
client.get('http://test.mrcdh.cn/api/index/info', {
// 这个头部是附带的
headers: {
'user-agent': userAgent,
}
}).then(res => {
console.log(res.data);
})
browser.close()
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
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
上次更新: 2023/09/22, 16:54:32