express
用nodejs写接口,网上大部分是使用的express,所以我就扒拉扒拉网上的资料,写了一个,方便以后自己copy。
在使用之前,别忘了把库安装一下,这个的前提是安装了node:
npm install express
npm install body-parser
完整的code如下:
const express = require("express");
const app = express();
const fs = require("fs");
const bodyParser = require("body-parser");
// 创建 application/json 解析
app.use(bodyParser.json());
// 创建 application/x-www-form-urlencoded 解析
app.use(bodyParser.urlencoded({ extended: true }));
//设置跨域访问
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();
});
app.post("/", function(req, res) {
res.send('get');
});
app.post("/", function(req, res) {
res.send('post');
});
//配置服务端口
var server = app.listen(8031, function() {
const host = server.address().address;
const port = server.address().port;
console.log("Example app listening at http://localhost:%s", port);
});
这里需要注意的是post请求的时候需要使用中间件body-parser,用来解析参数,这里有一篇讲这个中间件的文章:https://www.jianshu.com/p/ea0122ad1ac0,应该可以解决你的大部分疑问。
Koa2
Koa2是由express原班人马打造,感觉有接班人的感觉,好不太熟悉,下面有两个详细的教程,可以全面的学习Koa2:
https://chenshenhai.github.io/koa2-note/note/start/quick.html
https://www.itying.com/koa/article-index-id-79.html