这篇里是如何定义接口,我们一般访问接口如:post请求调用http://127.0.0.1:11000/webapi/userinfo/user 这个接口,成功返回用户信息,如果失败要返回失败原因等。

首先分析一下 /webapi/userinfo/login 接口。从这里可以看出 webapi是一个类,userinfo也是一个类,user是一个方法。再接合post、delete、put、get请求可以得到四个方法了,这样就可以实现增、删、改、查的功能。

接下我们就先创建一个webapi.js文件,里面的内容如下

const UserInfo = require('./UserInfo');
module.exports = {
userinfo: new UserInfo(),
};

再就是创建UserInfo.js,里面的内容:

/**
* 用户信息类
*
* @class UserInfo
*/
class UserInfo {
constructor(DbHelper, Utility) {
this.DbHelper = DbHelper;
this.Utility = Utility;
} post_login(request, response, options) { } get_user(request, response, options) {
response.Send({ msg: '这是一个get请求', options });
} post_user(request, response, options) {
response.Send({ msg: '这是一个 post 请求', options });
} delete_user(request, response, options) {
response.Send({ msg: '这是一个 delete 请求', options });
} put_user(request, response, options) {
response.Send({ msg: '这是一个 put 请求', options });
}
}
module.exports = UserInfo;

光这样写还是不行的啦,还要修改在上上篇中router里的代码,要不是调用不了接口的。

我们得还要建一个 index.js文件

// 这个是之前引用进来,这个就是/webapi部分
const webapi = require('./webapi');
// const order = require('./orderapi'); http://xxx/orderapi/list
// const car = require('./carapi'); http://xxx/car/goods
// const DealBusiness = require('./DealBusiness');
// ...
//
module.exports = {
webapi,
// order,car , DealBusiness: new DealBusiness() ,...
}

创建完这个文件好了后,在router里从require(index.js)文件了。通过匹配url路径中的匹配到定义好的接口。找了就调用相应的接口,没有找到的就向返回400等信息

定好了,就可以先用postman来试一下接口定义是否可以用了。下图是调用get请求的情况。

下面这张图是调用post请求返回的信息

这样接口调用基本就搞定啦。

这里完整把router.js里router类在这里放一下

class routes {
constructor(req, res) {
this.ApiInfo = api;
this.res = res;
this.req = req;
} initHeader() {
this.res.setHeader("Content-Type", "application/json;charset=utf-8");
this.res.setHeader("Access-Control-Allow-Origin", "*");
this.res.setHeader("access-control-allow-headers", "x-pingother, origin, x-requested-with, content-type, accept, xiaotuni,systemdate");
this.res.setHeader("access-control-allow-methods", "GET, POST, PUT, DELETE, OPTIONS");
this.res.setHeader("Access-Control-Expose-Headers", "date, token,systemdate");
this.res.setHeader('systemdate', new Date().getTime());
const { method } = this.req;
if (method && method === 'OPTIONS') {
this.res.end();
return;
} this.processRequestMethod(method);
} processRequestMethod(method) {
const PathInfo = path.parse(this.req.url);
if (!this.judgeIsCallApi(PathInfo)) {
return;
}
this.Method = method.toLocaleLowerCase();
this.parseUrlParams(); this.__ProcessApi(PathInfo);
} __ProcessApi(PathInfo) {
const methodInfo = { pathname: this.UrlInfo.pathname, method: this.Method };
// 以utf-8的形式接受body数据
this.req.setEncoding('utf8');
let __ReData = "";
// 这里接受用户调用接口时,向body发送的数据
this.req.on('data', (data) => {
__ReData += data;
});
const __self = this;
this.req.on('end', () => { // 监听数据接受完后事件。
// 查询用户定义好的接口。
const { func, ctrl } = __self.__FindMethod(PathInfo) || {};
const data = __ReData && __ReData !== '' ? JSON.parse(__ReData) : {};
if (func) {
func.apply(ctrl, [__self.req, __self.res, { params: __self.QueryParams, data }]);
return;
}
const _db = new DbHelper(); // 实例化一个数据库操作类
__self.ApiInfo.DealBusiness.Process(_db, __self.req, __self.res, { methodInfo, params: __self.QueryParams, data });
});
} judgeIsCallApi(PathInfo) {
if (PathInfo.ext === '') {
return true;
}
let charset = "binary";
switch (PathInfo.ext) {
case ".js":
this.res.writeHead(200, { "Content-Type": "text/javascript" });
break;
case ".css":
this.res.writeHead(200, { "Content-Type": "text/css" });
break;
case ".gif":
charset = "binary";
this.res.writeHead(200, { "Content-Type": "image/gif" });
break;
case ".jpg":
charset = "binary";
this.res.writeHead(200, { "Content-Type": "image/jpeg" });
break;
case ".png":
charset = "binary";
this.res.writeHead(200, { "Content-Type": "image/png" });
break;
default:
this.res.writeHead(200, { "Content-Type": "application/octet-stream" });
} const { dir, ext, name } = PathInfo;
const __abs = path.join(dir, name + ext);
const _pathInfo = [path.join('./server/', __abs), path.join('.', __abs)];
const __self = this;
let __fileIsExist = false;
for (let i = 0; i < _pathInfo.length; i++) {
const dir = _pathInfo[i];
__fileIsExist = fs.existsSync(dir);
if (__fileIsExist) {
fs.readFile(dir, (err, data) => {
if (err) {
__self.res.Send({ code: -1, msg: err.toString() });
} else {
__self.res.write(data, charset);
}
__self.res.end();
});
return false;
}
}
if (!__fileIsExist) {
__self.res.end();
}
return false;
} parseUrlParams() {
const _url = url.parse(this.req.url);
this.UrlInfo = _url;
const { query } = _url;
this.QueryParams = querystring.parse(query);
} __FindMethod(PathInfo, isSendMsg) {
const { pathname } = this.UrlInfo;
const pathList = pathname.split('/');
pathList.shift();
if (pathList.length === 1) {
if (isSendMsg) {
this.res.Send_404({ status: 404, msg: pathname + '接口没有找到' });
}
return null;
}
const __last = pathList.pop();
let __CallApi = this.ApiInfo[pathList[0]];
let __ApiIsExist = true;
for (let i = 1; i < pathList.length; i++) {
__CallApi = __CallApi[pathList[i]];
if (!__CallApi) {
__ApiIsExist = false;
break;
}
}
if (!__ApiIsExist) {
if (isSendMsg) {
this.res.Send_404({ status: 404, msg: pathname + '接口没有找到' });
}
return null;
}
const Controller = __CallApi;
__CallApi = __CallApi[this.Method + '_' + __last]
if (!__CallApi) {
if (isSendMsg) {
this.res.Send_404({ status: 404, msg: pathname + '接口没有找到' });
}
return null;
} return { func: __CallApi, ctrl: Controller };
}
}
module.exports = routes ;

现在接口的调用基本就OK了。

如果有什么不清楚,可以查看 https://github.com/xiaotuni/angular-map-http2 这里项目里具体写了怎么实现接口调用的

Angular4+NodeJs+MySQL 入门-03 后台接口定义的更多相关文章

  1. Angular4+NodeJs+MySQL 入门-05 接口调用

    接口调用 今天讲一下,如果在前端页面上通过调用后台接口,返回来的数据.把前面的几章结合起来. 这里所有用的代码在 https://github.com/xiaotuni/angular-map-htt ...

  2. Angular4+NodeJs+MySQL 入门-04 接口调用类

    上一篇文章说一下,后台接口的创建,这篇说一下如果调用接口. 创建一个目录helpers 此目录下有三个文件分别是 ApiClient.ts.clientMiddleware.ts.Core.ts,前面 ...

  3. Angular4+NodeJs+MySQL 入门-06 接口配置

    在上篇中说了怎么调用接口,这篇就来说说,接口配置吧. 后端是用NodeJS来写的,由于写后台(以前用的是C#语言)的时候,大部操作都在是对数据库表的增.删.改.查操作, 比如:根据查询出来的数据,然后 ...

  4. Angular4+NodeJs+MySQL 入门-01

    有一定的后台开发经验ES6语法.后台没有用框架来,纯自己写.会sql语句 安装NodeJS的安装 从网上下载 https://nodejs.org/en/ 选择自己,我用的是最新版本 Angular ...

  5. Angular4+NodeJs+MySQL 入门-02 MySql操作类

    NodeJs操作MySQL类 此类封装了几个常用的方法:插入,更新,删除,查询,开启事务,事务提交,事务回滚等操作.有一这个类,操作MYSQL就方便多了. 批处理,存储过程等方法还没有添加,因为觉得目 ...

  6. 把 nodejs koa2 制作的后台接口 部署到 腾讯云服务器

    我 使用 nodejs koa2框架 制作后端接口, 现在将nodejs koa2 部署到服务器 koa2项目 实现 接口 可以看我的 这篇文章: 简单实现 nodejs koa2 mysql 增删改 ...

  7. nginx+nodejs+mysql+memcached服务器后台架设centos6.5

    需要的下面四个工具最好都采用yum安装,不要采用编译安装的方法,因为编译安装会导致某些依赖关系丢失. nginx 作为HTTP和反向代理,处理静态页面,动态服务交由nodejs服务. nodejs作为 ...

  8. nodejs+mysql入门实例

    此前我已准备好mysql,使用的是PHP的组合包Appserv 手动添加数据库依赖: 在package.json的dependencies中新增, “mysql” : “latest”, { &quo ...

  9. nodejs+mysql入门实例(删)

    //连接数据库 var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'bdm253137448. ...

随机推荐

  1. 扫描工具——Meterpreter

    Meterpreter是Metasploit框架中的一个杀手锏,通常作为利用漏洞后的攻击载荷所使用,攻击载荷在触发漏洞后能够返回给用户一个控制通道.当使用Armitage.MSFCLI或MSFCONS ...

  2. Android使用Canvas画图

    1.参考:http://blog.csdn.net/rhljiayou/article/details/7212620/ 2.常用方法: 1.Canvas类 drawArc 绘制弧 drawBitma ...

  3. 在sql server数据库可以插入在回车的数据

    insert into t_FamilyClass (id,ParentId,Name) values(111,111,'111')可以在编辑模式下copy到editplus中,设置 显示 空白字符: ...

  4. loj #2116. 「HNOI2015」开店

    #2116. 「HNOI2015」开店 题目描述 风见幽香有一个好朋友叫八云紫,她们经常一起看星星看月亮从诗词歌赋谈到人生哲学.最近她们灵机一动,打算在幻想乡开一家小店来做生意赚点钱.这样的想法当然非 ...

  5. Python 简单说明与数据结构

    Python 简单说明与数据结构 Python 作为 "国内" 较流行的高级语言,具有代码容易理解.专注解决问题.混合编译其他语言的优点. 变量 变量是一个最基本的储存单位,它暂时 ...

  6. application的使用(实现计数器)

    application在整个WEB项目中共享使用数据. 常用方法: getAttribute(); setAttribute();示列: <%    Object count=applicati ...

  7. 12、OpenCV Python 图像梯度

    __author__ = "WSX" import cv2 as cv import numpy as np def lapalian_demo(image): #拉普拉斯算子 # ...

  8. 关于“java.lang.OutOfMemoryError : unable to create new native Thread”的报错问题

    好吧 我发誓这是postgresql的Mirroring Controller的RT测试的最后一个坑了. 在这个RT测试的最后,要求测试Mirroring Controller功能在长时间运行下的稳定 ...

  9. CentOS7.4关闭防火墙

    //临时关闭 systemctl stop firewalld //禁止开机启动 systemctl disable firewalld Removed symlink /etc/systemd/sy ...

  10. vector<vector<int>> 使用简单示例

    #include <iostream> #include <vector> using namespace std; int main() { vector<vector ...