vsCode当作node后台生成二维码
1.创建package.json文件
npm init -y
2.根目录下创建需要的index.js
3.启动index.js 终端: node index.js
4.保存自动启动index.js 终端下载: cnpm i nodemon -g
终端启动: nodemon
保存后自动启动index.js
5. 使用qr:
var qr = require('qr-image');
var fs = require('fs')
var qr_svg = qr.image('I love QR!', { type: 'png' });
qr_svg.pipe(fs.createWriteStream('你好.png'));
6.使用express模拟后台
下载cnpm i express --save
7.引入
var express = require('express')
var app = express()
app.listen(8989, () => {
console.log("程序已启动");
})
8.创建get请求
app.get('/qr', (req, res) => {
var code = qr.image('需要生成的字', { type: 'png' });
res.setHeader('Content-type', 'image/png');
code.pipe(res);
})
9.代码:
var qr = require('qr-image');
var fs = require('fs')
var express = require('express')
var app = express()
app.get('/qr', (req, res) => {
var code = qr.image('需要生成的字', { type: 'png' });
res.setHeader('Content-type', 'image/png');
code.pipe(res);
})
app.listen(8989, () => {
console.log("程序已启动");
})
10.可以通过 http://localhost:8989/qr 访问二维码
11.前端传不同的数字生成不同的二维码
index.js:
var code = qr.image(req.query.code, { type: 'png' });
在根目录创建index.html 传入参数
<img src="http://localhost:8989/qr?code=123123" alt="">
二:模拟后台接口:mock和express
1.需要express和mock (express之前已下载)
cnpm i mockjs --save
var mock = require('mockjs')
2.试一下接口
app.get('/userlist', (req, res) => {
res.json([11,22,33,44])
3.用mock造数据
let userList = mock.mock({
'list|10': [
{
'id|+1': 1,
name: "@cname",
city: "@city"
}
]
})
app.get('/userlist', (req, res) => {
res.json(userList)
})
4.前端传入数据,后台添加
app.get("/adduser", (req, res) => {
userList.push({
id: req.query.id,
name: req.query.name,
city: req.query.city,
})
res.json(true)
})
5.筛选数据:前端传入id后太筛选数据给前端
app.get('/userlist', (req, res) => {
let id = req.query.id
if (id) userList = userList.find(r => r.id === id)
res.json(userList)
})
代码:
var qr = require('qr-image');
var fs = require('fs')
var express = require('express')
var app = express()
var mock = require('mockjs')
let userList = mock.mock({
'list|10': [
{
'id|+1': 1,
name: "@cname",
city: "@city"
}
]
})
app.get('/userlist', (req, res) => {
let id = req.query.id
if (id) userList = userList.find(r => r.id === id)
res.json(userList)
})
app.get("/adduser", (req, res) => {
userList.push({
id: req.query.id,
name: req.query.name,
city: req.query.city,
})
res.json(true)
})
app.get('/qr', (req, res) => {
var code = qr.image(req.query.code, { type: 'png' });
res.setHeader('Content-type', 'image/png');
code.pipe(res);
})
app.listen(8989, () => {
console.log("程序已启动");
})