全局安装 wrangler
npm install -g @cloudflare/wrangler
初始化项目 qr
wrangler generate qr
添加 qr-image 依赖包
npm install qr-image
替换 index.js
内容
相比参考链接,有所修改,去除了
POST
请求,改为GET
请求获取参数
const qr = require('qr-image')
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
const landing = `
<form action="./" method="GET">
<input type="text" name="data" id="text" value="https://workers.dev">
<button type="submit">Generate QR Code</button>
</form>
`
const generate = data => {
const headers = { 'Content-Type': 'image/png' }
const qr_png = qr.imageSync(data || 'https://workers.dev')
return new Response(qr_png, { headers })
}
async function handleRequest(request) {
let response
const url = new URL(request.url)
if (url.pathname === '/' && !url.searchParams.has('data')) {
response = new Response(landing, {
headers: { 'Content-Type': 'text/html' },
})
} else if (url.pathname === '/' && url.searchParams.has('data')) {
response = generate(url.searchParams.get('data'))
} else {
response = new Response('404', {
status: '404',
headers: { 'Content-Type': 'text/html' },
})
}
return response
}
修改配置文件 wrangler.toml
name = "qr"
type = "webpack"
account_id = ""
workers_dev = true
route = ""
zone_id = ""
type 值修改为 webpack, account_id 必填,修改成你的自己的。
登录 https://dash.cloudflare.com 后面的一段32位字符串就是 account_id
发布
wrangler publish
在线查看 https://qr.fun.workers.dev/
参考链接:
https://github.com/signalnerve/workers-qr-code-generator/
https://developers.cloudflare.com/workers/tutorials/build-a-qr-code-generator