目录
一、准备工作
初始化一个项目(npm init),主要是安装依赖express,实现后续接口。
二、核心代码
新建一个js文件,利用express实现请求接口,以下是主要代码。
const express = require('express')
const app = express()
//设置跨域访问
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
三、get请求
// 处理前端所需数据 - 随便搞
let list = []
function template(id) {
let heroes = ['张三', '李四', '王五', '赵六', '钱七', '路人甲', '路人乙'];
return {
id: id,
uname: heroes[Math.floor(Math.random() * 7)],
age: Math.floor(Math.random()*100)
}
}
for (let i = 0; i < 10; i++) {
list.push(template(i))
}
// get请求
app.get('/node-post', (req, res) => {
// 响应参数
res.send(list)
})
四、post请求
node实现接口目的就是为了实现联调的效果,其实get请求就足够了。
// 解析post参数
const bodyParser = require("body-parser");//body参数解析
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// post请求
app.post('/node-post', (req, res) => {
// 请求参数- req 就是前端传给后端的参数,这里可以直接返回看一下
res.send(req.body)
})
五、配置服务端口
// 配置服务端口 端口号不要被占用
app.listen(3000, () => {
console.log('app listening on port 3000!');
})
六、完整代码
const express = require('express')
const app = express()
//设置跨域访问
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
// 解析post参数
const bodyParser = require("body-parser");//body参数解析
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 处理数据
let list = []
function template(id) {
let heroes = ['张三', '李四', '王五', '赵六', '钱七', '路人甲', '路人乙', 'bruse Lee'];
return {
id: id,
uname: heroes[Math.floor(Math.random() * 7)],
age: Math.floor(Math.random()*100)
}
}
for (let i = 0; i < 10; i++) {
list.push(template(i))
}
// get请求
app.get('/node-get', (req, res) => {
// 拿到请求参数
console.log(req.params)
// res.status(200),
res.send(list)
})
// post请求
// app.use(express.urlencoded())
app.post('/node-post', (req, res) => {
// 拿到请求参数
console.log(req.body)
res.send(req.body)
})
// 配置服务端口
app.listen(3000, () => {
console.log('app listening on port 3000!');
})
七、启动 验证
直接命令 node 启动,终端中有打印配置服务端口时写的打印结果,证明启动成功。
这里为了方便验证,用简单的原生html+jquery实现接口验证是否成功
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<body>
<button id="box">点击发送get请求</button>
<button id="butt">点击发送post请求</button>
<script>
var btn = document.querySelector('#box')
btn.onclick = function () {
$.ajax({
type: 'get',
url: 'http://127.0.0.1:3000/node-get',
success: (res) => {
console.log(res, 'get请求成功!')
}
})
}
var btn2 = document.querySelector('#butt')
btn2.onclick = function () {
$.ajax({
type: 'post',
url: 'http://127.0.0.1:3000/node-post',
data: {
uname: 'admin',
password: '123456'
},
success: (res) => {
console.log(res, 'post请求成功!')
}
})
}
</script>
</body>
</html>
点击按钮,两种请求数据返回成功,网络响应也都正常。
到这里简单的node实现接口就算完成了,快去试试吧。