利用express写api接口

 1 // 导入模块
 2 const express = require("express");
 3 // 生成服务器
 4 const app = express();
 5 
//jsonp请求 6 app.get("/api/jsonp", (req, res) => { 7 // 拿到客户端请求的回调函数 8 const funcName = req.query.callback; 9 // 要返回给客户端的数据 10 const data = { name: "zs", age: 18, gender: "male" }; 11 // 拼接字符串 12 const DataStr = `${funcName}(${JSON.stringify(data)})`; 13 // 返回给客户端 14 res.send(DataStr); 15 }); 16
//解决跨域请求的问题 cors 设置了请求头 17 // 导入中间件 18 const cors = require("cors"); 19 // 配置中间件 20 app.use(cors()); 21 // 配置表单数据的中间件 必须要配置这个才可以拿到客户端post请求发过来的url-encoded 格式的数据 22 app.use(express.urlencoded({ extended: false })); 23 24 // 1--导入router路由模块 25 const router = require("./routerApi"); 26 // 2--挂载到全局中间件上 27 app.use("/api", router); 28 29 // 开启服务器 30 app.listen(80, () => console.log("http://127.0.0.1"));

路由模块

 1 const router = require("express").Router();
 2 
 3 // get 请求
 4 router.get("/get", (req, res) => {
 5   // 获取客户端通过查询字符串 发送到服务器的数据
 6   const query = req.query;
 7   res.send({
 8     status: 0, //0表示处理成功
 9     msg: "GET请求成功",
10     data: query, //把请求的数据 再响应给客户端
11   });
12 });
13 // post 请求
14 router.post("/post", (req, res) => {
15   const body = req.body;
16   res.send({
17     status: 0, //0表示处理成功
18     msg: "POST请求成功",
19     data: body, //把请求的数据 再响应给客户端
20   });
21 });
22 
//将模块暴露出去 23 module.exports = router;
原文地址:https://www.cnblogs.com/ndh074512/p/14870990.html