在找工作的时候,都会用 boss 直聘、拉钩之类的 APP 投简历。
根据职位描述筛选出适合自己的来投。
此外,职位描述也是简历优化的方向,甚至是平时学习的方向。
所以我觉得招聘网站的职位描述还是挺有价值的,就想把它们都爬取下来存到数据库里。
本文一起来实现下。
爬取数据使用 Puppeteer 来做,然后用 TypeORM 把爬到的数据存到 mysql 表里。
创建个项目:
mkdir jd-spider
cd jd-spider
npm init -y进入项目,安装 puppeteer:
npm install --save puppeteer要爬取的是 boss 直聘的网站数据。
首先,进入搜索页面,选择全国范围,搜索前端:
然后职位列表的每个点进去查看描述,把这个岗位的信息和描述抓取下来:
创建 test.js
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({
headless: false,
defaultViewport: {
width: 0,
height: 0
}
});
const page = await browser.newPage();
await page.goto('https://www.zhipin.com/web/geek/job');
await page.waitForSelector('.job-list-box');
await page.click('.city-label', {
delay: 500
});
await page.click('.city-list-hot li:first-child', {
delay: 500
});
await page.focus('.search-input-box input');
await page.keyboard.type('前端', {
delay: 200
});
await page.click('.search-btn', {
delay: 1000
});调用 launch 跑一个浏览器实例,指定 headless 为 false 也就是有界面。
defaultView 设置 width、height 为 0 是网页内容充满整个窗口。
然后就是自动化的流程了:
首先进入职位搜索页面,等 job-list-box 这个元素出现之后,也就是列表加载完成了。
就点击城市选择按钮,选择全国。
然后在输入框输入前端,点击搜索。
然后跑一下。
跑之前在 package.json 设置 type 为 module,也就是支持 es module 的 import:
node ./test.js它会自动打开一个浏览器窗口:
然后执行自动化脚本:
这样,下面的列表数据就是可以抓取的了。
不过这里其实没必要这么麻烦,因为只要你 url 里带了 city 和 query 的参数,会自动设置为搜索参数:
所以直接打开这个 url 就可以:
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({
headless: false,
defaultViewport: {
width: 0,
height: 0
}
});
const page = await browser.newPage();
await page.goto('https://www.zhipin.com/web/geek/job?query=前端&city=100010000');
await page.waitForSelector('.job-list-box');然后要拿到页数,用来访问列表的每页数据。
怎么拿到页数呢?
其实就是拿 options-pages 的倒数第二个 a 标签的内容:
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({
headless: false,
defaultViewport: {
width: 0,
height: 0
}
});
const page = await browser.newPage();
await page.goto('https://www.zhipin.com/web/geek/job?query=前端&city=100010000');
await page.waitForSelector('.job-list-box');
const res = await page.$eval('.options-pages a:nth-last-child(2)', el => {
return parseInt(el.textContent)
});
console.log(res);$eval 第一个参数是选择器,第二个参数是对选择出的元素做一些处理后返回。
跑一下:
页数没问题。
然后接下来就是访问每页的列表数据了。
就是在 url 后再带一个 page 的参数:
然后,遍历访问每页数据,拿到每个职位的信息:
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({
headless: false,
defaultViewport: {
width: 0,
height: 0
}
});
const page = await browser.newPage();
await page.goto('https://www.zhipin.com/web/geek/job?query=前端&city=100010000');
await page.waitForSelector('.job-list-box');
const totalPage = await page.$eval('.options-pages a:nth-last-child(2)', e => {
return parseInt(e.textContent)
});
const allJobs = [];
for(let i = 1; i <= totalPage; i ++) {
await page.goto('https://www.zhipin.com/web/geek/job?query=前端&city=100010000&page=' + i);
await page.waitForSelector('.job-list-box');
const jobs = await page.$eval('.job-list-box', el => {
return [...el.querySelectorAll('.job-card-wrapper')].map(item => {
return {
job: {
name: item.querySelector('.job-name').textContent,
area: item.querySelector('.job-area').textContent,
salary: item.querySelector('.salary').textContent
},
link: item.querySelector('a').href,
company: {
name: item.querySelector('.company-name').textContent,
}
}
})
});
allJobs.push(...jobs);
}
console.log(allJobs);具体的信息都是从 dom 去拿的:
跑一下试试:
可以看到,它会依次打开每一页,然后把职位数据爬取下来。
做到这一步还不够,要点进去这个链接,拿到 jd 的描述。
for(let i = 0; i< allJobs.length; i ++) {
await page.goto(allJobs[i].link);
try{
await page.waitForSelector('.job-sec-text');
const jd= await page.$eval('.job-sec-text', el => {
return el.textContent
});
allJobs[i].desc = jd;
console.log(allJobs[i]);
} catch(e) {}
}
try catch 是因为有的页面可能打开会超时导致中止,这种就直接跳过好了。
跑一下:
它同样会自动打开每个岗位详情页,拿到职位描述的内容,并打印在控制台。
接下来只要把这些存入数据库就好了。
新建个 nest 项目:
npm install -g @nestjs/cli
nest new boss-jd-spider用 docker 把 mysql 跑起来:
从 docker 官网下载 docker desktop,这个是 docker 的桌面端:
跑起来后,搜索 mysql 镜像(这步需要科学上网),点击 run:
输入容器名、端口映射、以及挂载的数据卷,还要指定一个环境变量:
端口映射就是把宿主机的 3306 端口映射到容器里的 3306 端口,这样就可以在宿主机访问了。
数据卷挂载就是把宿主机的某个目录映射到容器里的 /var/lib/mysql 目录,这样数据是保存在本地的,不会丢失。
而 MYSQL_ROOT_PASSWORD 的密码则是 mysql 连接时候的密码。
跑起来后,用 GUI 客户端连上,这里用的是 mysql workbench,这是 mysql 官方提供的免费客户端:
连接上之后,点击创建 database:
指定名字、字符集为 utf8mb4,然后点击右下角的 apply。
创建成功之后在左侧就可以看到这个 database 了:
当然,现在还没有表。
在 Nest 里用 TypeORM 连接 mysql。
安装用到的包:
npm install --save @nestjs/typeorm typeorm mysql2mysql2 是数据库驱动,typeorm 是用的 orm 框架,而 @nestjs/typeorm 是 nest 集成 typeorm 用的。
在 AppModule 里引入 TypeORM,指定数据库连接配置:
TypeOrmModule.forRoot({
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "guang",
database: "boss-spider",
synchronize: true,
logging: true,
entities: [],
poolSize: 10,
connectorPackage: 'mysql2',
extra: {
authPlugin: 'caching_sha2_password',
}
}),然后创建个 entity:
src/entities/Job.ts
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class Job {
@PrimaryGeneratedColumn()
id: number;
@Column({
length: 30,
comment: '职位名称'
})
name: string;
@Column({
length: 20,
comment: '区域'
})
area: string;
@Column({
length: 10,
comment: '薪资范围'
})
salary: string;
@Column({
length: 600,
comment: '详情页链接'
})
link: string;
@Column({
length: 30,
comment: '公司名'
})
company: string;
@Column({
type: 'text',
comment: '职位描述'
})
desc: string;
}链接可能很长,所以设置为 600,而职位描述就更长了,直接设置 text 就行,它可以存储大段文本。
在 AppModule 引入:
把服务跑起来:
npm run start:devTypeORM会自动建表:
然后加个启动爬虫的接口:
@Get('start-spider')
startSpider() {
this.appService.startSpider();
return '爬虫已启动';
}安装 puppeteer:
npm install --save puppeteer在 AppService 里实现 startSpider:
import { Injectable } from '@nestjs/common';
import puppeteer from 'puppeteer';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
async startSpider() {
const browser = await puppeteer.launch({
headless: true,
defaultViewport: {
width: 0,
height: 0
}
});
const page = await browser.newPage();
await page.goto('https://www.zhipin.com/web/geek/job?query=前端&city=100010000');
await page.waitForSelector('.job-list-box');
const totalPage = await page.$eval('.options-pages a:nth-last-child(2)', e => {
return parseInt(e.textContent)
});
const allJobs = [];
for(let i = 1; i <= totalPage; i ++) {
await page.goto('https://www.zhipin.com/web/geek/job?query=前端&city=100010000&page=' + i);
await page.waitForSelector('.job-list-box');
const jobs = await page.$eval('.job-list-box', el => {
return [...el.querySelectorAll('.job-card-wrapper')].map(item => {
return {
job: {
name: item.querySelector('.job-name').textContent,
area: item.querySelector('.job-area').textContent,
salary: item.querySelector('.salary').textContent
},
link: item.querySelector('a').href,
company: {
name: item.querySelector('.company-name').textContent
}
}
})
});
allJobs.push(...jobs);
}
// console.log(allJobs);
for(let i = 0; i< allJobs.length; i ++) {
await page.goto(allJobs[i].link);
try{
await page.waitForSelector('.job-sec-text');
const jd= await page.$eval('.job-sec-text', el => {
return el.textContent
});
allJobs[i].desc = jd;
console.log(allJobs[i]);
} catch(e) {}
}
}
}这里原封不动的把之前的爬虫逻辑复制了过来,只是把 headless 设置为了 true,因为不需要界面。
浏览器访问下:
爬虫跑的没啥问题。
不过这个过程中 boss 可能会检测到你访问频率过高,会让你做下是不是真人的验证:
这个就是验证码点点就好了。
然后把数据存到数据库里:
用 EntityManager 来 save 就好了:
@Inject(EntityManager)
private entityManager: EntityManager;const job = new Job();
job.name = allJobs[i].job.name;
job.area = allJobs[i].job.area;
job.salary = allJobs[i].job.salary;
job.link = allJobs[i].link;
job.company = allJobs[i].company.name;
job.desc = allJobs[i].desc;
await this.entityManager.save(Job, job);再跑下:
去数据库里看下:
这样,你就可以对这些职位描述做一些搜索,分析之类的了。
比如搜索职位描述中包含 react 的岗位:
SELECT * FROM `boss-spider`.job where `desc` like "%React%";这样,爬虫就做完了。
如果想在前端实时看到爬取到的数据,可以通过 SSE 来实时返回:
这样用:
这里就不改了。
通过 puppeteer 实现了对 BOSS 直聘网站的前端职位的爬取,并用 Nest + TypeORM 把数据保存到了数据库里。
这样就可以在本地对这些职位数据做一些处理或分析了。
扫码登录是常见的功能,基本各种网站都支持。
比如掘金的登录就支持 APP 扫码的方式:
如果你 APP 没登录,扫码后会跳到登录页面:
登录之后,会进入确认界面,你可以选择授权登录或者取消:
这边确认之后,pc 网站就登录了。
知乎,b 站等也是这样的:
有没有感觉很神奇,为什么一扫二维码,然后确认下,那边就自动登录了呢?
其实原理也很简单。
先用解析工具解码下二维码的内容:
可以看到,二维码的内容是一个 url,如果在手机浏览器打开,是这样的:
会让你下载 APP。
而在 APP 里打开,就是登录确认界面了:
那确认的是哪个二维码呢?
二维码这里是有个唯一 id 的,通过这个 id 就知道是哪个二维码。
这个二维码有 5 个状态:
最开始是未扫描状态:
扫码后会进入等待用户确认状态:
确认后会进入同意授权状态:
取消的话会进入取消授权状态:
长时间不操作会进入过期状态:
也就是说,扫码后进行不同的操作就是修改这个 id 对应的二维码的状态。
另一边修改了状态,这边是怎么知道二维码状态变了呢?
websocket 么?
不用,一般都是轮询来做。
比如掘金:
二维码出现后,会有一个每秒一次的轮询请求来查询二维码状态:
最开始是 new:
扫码后会变成 scanned:
知乎也是一样:
这时候,手机会进入登录确认页面:
bilibili 的登录确认页面:
知乎的登录确认页面:
这边点击确认登录或者取消之后,会发请求修改 id 对应的二维码的状态。
那边一直在轮询,自然就知道了二维码状态的变更。
也就是这样的:
服务端有个 qrcode/generate 接口,会生成一个随机的二维码 id,存到 redis 里,并返回二维码。
还有个 qrcode/check 接口,会返回 redis 里的二维码状态,浏览器里可以轮询这个接口拿到二维码状态。
然后手机 APP 扫码之后,如果没登录,会先跳转到登录页面,登录之后会进入登录确认页面。
这个时候就从二维码中拿到了 id,然后调用 qrcode/scan、qrcode/cancel、qrcode/confirm 就是修改二维码为不同的状态。
这时候用户是登录了的,jwt 的登录认证方式会携带 token,服务端只要从 token 中取出用户信息,存入 redis 即可。
然后另一边的轮询接口发现是确认状态,会根据用户信息生成 jwt 返回。
这样,手机 APP 里确认之后,pc 的浏览器就自动登录了该用户账号。
这里的 jwt 是保存登录状态的一种方案,会把用户信息放在 token 里返回,然后每次访问接口带上 authorization 的 header,携带 token。
思路理清了,来实现一下吧!
创建个 nest 项目:
npm install -g @nestjs/cli
nest new qrcode-login把它跑起来:
npm run start:dev浏览器访问 http://localhost:3000 就可以看到 hello world,就代表服务跑起来了:
然后实现下生成二维码的接口:
安装下用到的包:
npm install qrcode @types/qrcode添加一个路由:
import { randomUUID } from 'crypto';
import * as qrcode from 'qrcode';@Get('qrcode/generate')
async generate() {
const uuid = randomUUID();
const dataUrl = await qrcode.toDataURL(uuid);
return {
qrcode_id: uuid,
img: dataUrl
}
}这里用 node 的 crypto 模块生成一个随机的 uuid。
然后用 qrcode 生成二维码,只不过转成 base64 返回。
在 html 里把它渲染出来看一下:
新建 static/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>扫码登录</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<img src="data:image/png;base64,这里填入你生成的 url" alt=""/>
</body>
</html>
然后在 main.ts 里支持这个目录下静态资源的访问,用 pages 作为前缀:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.useStaticAssets('static', { prefix: '/pages'});
await app.listen(3000);
}
bootstrap();这样你访问 http://localhost:3000/pages/index.html 就可以看到二维码了:
用在线解码工具解码下看看:
确实,内容就是生成的 uuid。
然后,其实这个二维码扫出的应该是个网址。
比如掘金的二维码解析出的内容:
如果用手机浏览器扫这个码的话,打开的就是下载 APP 的页面:
而如果用掘金 APP 扫码,扫出的就是登录确认页面了:
这个很正常,因为如果随便一个浏览器都能扫码打开登录确认页面,那谁还下载掘金 APP 呢?
所以掘金的二维码只能掘金 APP 扫,微信的二维码只能用微信 APP 扫。
这个页面做了检查,判断是 APP 打开的还是其他方式打开的,分别会显示不同的内容。
这里也改成一个 url:
扫码就会打开这个页面,而这个页面就是登录确认页面。
写一下这个页面:
新建 static/confirm.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>扫码登录确认</title>
</head>
<body>
<button>确认登录</button>
<button>取消</button>
</body>
</html>但这里有个问题,开发服务是在电脑上的,手机怎么访问呢?
这里需要用 charles 来做代理:
下载 charles,打开
让电脑和手机连接同一个 wifi,然后在手机的 wifi 设置那里设置代理:
代理的 ip 是电脑 ip,端口号就是 charles 代理服务的默认端口 8888
这时候电脑上会收到连接提醒,同意下就好了:
然后手机就可以访问电脑上的 nest 服务:
看到这个 hello world 了没?
这就是电脑上的这个 nest 服务返回的:
那个登录确认页面在电脑访问是这样的:
然后我把二维码的内容改为这个:
修改下展示二维码的页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>扫码登录</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/axios@1.5.0/dist/axios.min.js"></script>
</head>
<body>
<img id="img" src="" alt=""/>
<script>
axios.get('http://localhost:3000/qrcode/generate').then(res => {
document.getElementById('img').src = res.data.img;
})
</script>
</body>
</html>用 axios 请求生成二维码的接口,然后修改图片 src。
用手机扫码下:
用微信扫码,可以看到,打开了登录确认页面。
按钮有点小,设置下样式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>扫码登录确认</title>
<style>
#info {
height: 400px;
line-height: 400px;
font-size: 20px;
padding: 20px;
}
#confirm, #cancel{
display: block;
width: 80%;
line-height: 40px;
font-size: 20px;
margin-bottom: 20px;
}
#confirm {
background: skyblue;
}
</style>
</head>
<body>
<div id="info">
是否确认登录 xxx 网站?
</div>
<button id="confirm">确认登录</button>
<button id="cancel">取消</button>
</body>
</html>好看多了。
二维码的内容解码后是这样的:
然后来实现剩下的接口:
生成二维码之后,要在 redis 里保存一份,这里简化一下,直接用个 map 保存吧。
const map = new Map<string, QrCodeInfo>();
interface QrCodeInfo{
status: 'noscan' | 'scan-wait-confirm' | 'scan-confirm' | 'scan-cancel' | 'expired',
userInfo?: {
userId: number;
}
}
// noscan 未扫描
// scan-wait-confirm 已扫描,等待用户确认
// scan-confirm 已扫描,用户同意授权
// scan-cancel 已扫描,用户取消授权
// expired 已过期map.set(`qrcode_${uuid}`, {
status: 'noscan'
});然后加一个 qrcode/check 接口,用来查询二维码状态:
@Get('qrcode/check')
async check(@Query('id') id: string) {
return map.get(`qrcode_${id}`);
}测试下:
访问 /qrcode/generate 生成二维码和 id
然后访问 /qrcode/check 拿到这个 id 的状态:
然后再实现 /qrcode/confirm、/qrcode/cancel、/qrcode/scan 这三个接口:
@Get('qrcode/scan')
async scan(@Query('id') id: string) {
const info = map.get(`qrcode_${id}`);
if(!info) {
throw new BadRequestException('二维码已过期');
}
info.status = 'scan-wait-confirm';
return 'success';
}
@Get('qrcode/confirm')
async confirm(@Query('id') id: string) {
const info = map.get(`qrcode_${id}`);
if(!info) {
throw new BadRequestException('二维码已过期');
}
info.status = 'scan-confirm';
return 'success';
}
@Get('qrcode/cancel')
async cancel(@Query('id') id: string) {
const info = map.get(`qrcode_${id}`);
if(!info) {
throw new BadRequestException('二维码已过期');
}
info.status = 'scan-cancel';
return 'success';
}测试下:
先 qrcode/generate 生成二维码,拿到 id:
然后调用 qrcode/scan 修改状态,之后调用 qrcode/check 查询下状态:
同样的方式测试 qrcode/cancel 和 qrcode/confirm 接口:
如果 id 不存在,会返回 400 的状态码:
然后就可以在 static/index.html 里加上 qrcode/check 接口来轮询二维码状态了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>扫码登录</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/axios@1.5.0/dist/axios.min.js"></script>
</head>
<body>
<img id="img" src="" alt=""/>
<div id="info"></div>
<script>
axios.get('http://localhost:3000/qrcode/generate').then(res => {
document.getElementById('img').src = res.data.img;
queryStatus(res.data.qrcode_id);
})
function queryStatus(id) {
axios.get('http://localhost:3000/qrcode/check?id=' + id).then(res => {
const status = res.data.status;
let content = '';
switch(status) {
case 'noscan': content = '未扫码'; break;
case 'scan-wait-confirm': content = '已扫码,等待确认'; break;
case 'scan-confirm': content = '已确认'; break;
case 'scan-cancel': content = '已取消'; break;
}
document.getElementById('info').textContent = content;
if(status === 'noscan' || status === 'scan-wait-confirm') {
setTimeout(() => queryStatus(id), 1000);
}
})
}
</script>
</body>
</html>生成二维码之后,就开始轮询状态了。
根据状态分别显示不同的文字,如果不是已确认或者已取消就在一秒后继续下次轮询。
然后,在登录确认页面也加上接口调用:
改下 static/confirm.html
使用 URLSearchParams 的 api 拿到 url 中的 id:
然后修改这个 id 对应的二维码的状态。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>扫码登录确认</title>
<script src="https://unpkg.com/axios@1.5.0/dist/axios.min.js"></script>
<style>
#info {
height: 400px;
line-height: 400px;
font-size: 20px;
padding: 20px;
}
#confirm, #cancel{
display: block;
width: 80%;
line-height: 40px;
font-size: 20px;
margin-bottom: 20px;
}
#confirm {
background: skyblue;
}
</style>
</head>
<body>
<div id="info">
是否确认登录 xxx 网站?
</div>
<button id="confirm">确认登录</button>
<button id="cancel">取消</button>
<script>
const params = new URLSearchParams(window.location.search.slice(1));
const id = params.get('id');
axios.get('http://192.168.31.56:3000/qrcode/scan?id=' + id).catch(e => {
alert('二维码已过期');
});
document.getElementById('confirm').addEventListener('click', () => {
axios.get('http://192.168.31.56:3000/qrcode/confirm?id=' + id).catch(e => {
alert('二维码已过期');
});
});
document.getElementById('cancel').addEventListener('click', () => {
axios.get('http://192.168.31.56:3000/qrcode/cancel?id=' + id).catch(e => {
alert('二维码已过期');
});
});
</script>
</body>
</html>进入这个页面,就访问 qrcode/scan 接口,来把 id 对应的二维码改为已扫描状态。
点击确认或者取消按钮也分别修改状态为确认和取消。
注意,这个页面是在手机打开的,需要通过 ip 的方式访问接口。
测试下:
打开页面后,生成二维码,这时候就开始轮询二维码状态。
手机扫码,进入登录确认页面。
这时候二维码页面的状态变为了等待确认:
然后确认登录,这时候 pc 页面变为了已确认状态:
如果点击取消,那就会变为已取消状态:
这就是扫码之后,pc 上的二维码同步改变状态的原理。
当然,最终是要做登录的。
确认之后,就要拿到这边的登录状态,从中取出用户信息。
当然,现在还没做登录。
通过 jwt 搞一下:
引入 jwt 的 包:
npm install @nestjs/jwt在 AppModule 里引入它:
然后实现登录接口:
这里没有用数据库,只有 2 个用户,如果信息匹配,就返回 jwt 的 token:
@Inject(JwtService)
private jwtService: JwtService;
private users = [
{id: 1, username: 'dong', password: '111'},
{id: 2, username: 'guang', password: '222'},
];
@Get('login')
async login(@Query('username') username: string, @Query('password') password: string) {
const user = this.users.find(item => item.username === username);
if(!user) {
throw new UnauthorizedException('用户不存在');
}
if(user.password !== password) {
throw new UnauthorizedException('密码错误');
}
return {
token: await this.jwtService.sign({
userId: user.id
})
}
}postman 里测试下:
登录成功后,会返回 token。
这个 token 一般都是在访问接口的时候放在 authorization 的 header 里,通过 Bearer xxx 的方式。
添加一个 userInfo 的接口来拿到用户信息:
@Get('userInfo')
async userInfo(@Headers('Authorization') auth: string) {
try{
const [, token] = auth.split(' ');
const info = await this.jwtService.verify(token);
const user = this.users.find(item => item.id == info.userId);
return user;
} catch(e) {
throw new UnauthorizedException('token 过期,请重新登录');
}
}它会从 header 中取出 token,解析出其中的信息,从而拿到 userId,然后查询 id 对应的用户信息返回。
加上 authorization 的 header,访问下 userInfo 接口:
可以看到,拿到了用户的信息。
然后在登录确认页面加上登录:
添加两个按钮:
这俩按钮分别是登录不同的账号,拿到 token:
访问 confirm 接口时带上这个 token:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>扫码登录确认</title>
<script src="https://unpkg.com/axios@1.5.0/dist/axios.min.js"></script>
<style>
#info {
height: 400px;
line-height: 400px;
font-size: 20px;
padding: 20px;
}
#confirm, #cancel{
display: block;
width: 80%;
line-height: 40px;
font-size: 20px;
margin-bottom: 20px;
}
#confirm {
background: skyblue;
}
</style>
</head>
<body>
<button id="guang">登录光光账号</button>
<button id="dong">登录东东账号</button>
<div id="info">
是否确认登录 xxx 网站?
</div>
<button id="confirm">确认登录</button>
<button id="cancel">取消</button>
<script>
const params = new URLSearchParams(window.location.search.slice(1));
const id = params.get('id');
let token = '';
document.getElementById('dong').addEventListener('click', () => {
axios.get('http://192.168.31.56:3000/login', {
params: {
username: 'dong',
password: '111'
}
}).then(res => {
token = res.data.token;
});
});
document.getElementById('guang').addEventListener('click', () => {
axios.get('http://192.168.31.56:3000/login', {
params: {
username: 'guang',
password: '222'
}
}).then(res => {
token = res.data.token;
});
});
axios.get('http://192.168.31.56:3000/qrcode/scan?id=' + id).catch(e => {
alert('二维码已过期');
});
document.getElementById('confirm').addEventListener('click', () => {
axios.get('http://192.168.31.56:3000/qrcode/confirm?id=' + id, {
headers: {
authorization: 'Bearer ' + token
}
}).catch(e => {
alert('二维码已过期');
});
});
document.getElementById('cancel').addEventListener('click', () => {
axios.get('http://192.168.31.56:3000/qrcode/cancel?id=' + id).catch(e => {
alert('二维码已过期');
});
});
</script>
</body>
</html>然后在 qrcode/confirm 接口里把 token 取出来,拿到其中的用户信息,保存到 map 里:
@Get('qrcode/confirm')
async confirm(@Query('id') id: string, @Headers('Authorization') auth: string) {
let user;
try{
const [, token] = auth.split(' ');
const info = await this.jwtService.verify(token);
user = this.users.find(item => item.id == info.userId);
} catch(e) {
throw new UnauthorizedException('token 过期,请重新登录');
}
const info = map.get(`qrcode_${id}`);
if(!info) {
throw new BadRequestException('二维码已过期');
}
info.status = 'scan-confirm';
info.userInfo = user;
return 'success';
}这样,当扫码确认后,那边就能拿到用户信息:
改下 static/index.html
确认的时候展示下登录用户的信息:
加上登录之后,再测试下:
手机扫码,点击登录光的账号,然后确认登录:
刷新页面,重新扫码,然后登录东东账号。
这时候 pc 网站就显示了当前登录用户是 dong
当然,登录状态需要一个 jwt,返回下就好了。
@Get('qrcode/check')
async check(@Query('id') id: string) {
const info = map.get(`qrcode_${id}`);
if(!info) {
throw new BadRequestException('二维码已过期');
}
if(info.status === 'scan-confirm') {
return {
token: await this.jwtService.sign({
userId: info.userInfo.userId
}),
...info
}
}
return info;
}这样,当那边确认登录之后,这边就拿到了 jwt 的 token,也就是完成了登录了:
对比下掘金的扫码登录流程:
是不是一模一样?
扫码登录就是这样实现的。
案例代码上传了
扫码登录是常用的功能,掘金、知乎、b 站等各大网站都有。
流程是在 pc 选择扫码登录的方式,用 APP 扫码,在 app 上登录之后进入登录确认页面。
可以点击确认登录或者取消,如果确认登录,那 pc 网站就会自动登录该账号。
它的实现原理是这样的:
pc 端生成二维码,然后不断轮询二维码状态。
APP 里扫码拿到 qrcode_id,然后分别调用 scan、confirm、cancel 来修改二维码状态。
并且登录之后会把 token 带过去。
在 redis 里保存着二维码的状态和用户信息,然后这边确认之后,另一边就可以用 userInfo 生成 jwt 的 token,从而实现登录。
这就是扫码登录的实现原理。