用到的node库
- express 用来启动服务
- qrcode 用来生成二维码
- cors 来解决跨域问题
代码展示
const qrcode = require('qrcode');
const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors());
app.get('/qrcode', (req, res) => {
const query = req.query;
console.log(query)
qrcode.toDataURL(query.text, (err, src) => {
if (err) return res.send('Error occured');
res.json({ src });
res.end();
});
})
app.listen(port, () => {
console.log(`服务器正在运行,访问 http://localhost:${port}`);
});
<body>
<input type="text" id="input">
<button id="btn">发送</button>
<img src="" id="img" alt="">
<script>
var input = document.getElementById('input');
var img = document.getElementById('img');
var btn = document.getElementById('btn');
btn.onclick = function(){
fetch('http://localhost:3000/qrcode?text=' + input.value)
.then(res=>res.json())
.then(data=>{
console.log(data)
img.src = data.src
}).catch(err=>{
console.log('---err')
})
}
</script>
</body>
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/a047f9b98286422aabd812e6585209ed.png)