nodejs写接口

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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值