这篇里是如何定义接口,我们一般访问接口如: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. python DDT读取excel测试数据

    转自:http://www.cnblogs.com/nuonuozhou/p/8645129.html ddt   结合单元测试一起用 ddt(data.driven.test):数据驱动测试 由外部 ...

  2. POJ - 2965 The Pilots Brothers' refrigerator(压位+bfs)

    The game “The Pilots Brothers: following the stripy elephant” has a quest where a player needs to op ...

  3. canvas基本绘制图形

    canvas H5新增的元素,提供了强大的图形的绘制,变换,图片,视频的处理等等.需要使用JavaScript脚本操作 浏览器支持 大多数的现代浏览器都可以支持:IE8以下的浏览器不支持 画布 可支持 ...

  4. 使用Boost库(1)

    如何说服你的公司.组织使用Boost库 one of the most highly regarded and expertly designed C++ library projects in th ...

  5. Lucene的基本概念----转载yufenfei的文章

    Lucene的基本概念 Lucene是什么? Lucene是一款高性能.可扩展的信息检索工具库.信息检索是指文档搜索.文档内信息搜索或者文档相关的元数据搜索等操作. 信息检索流程如下: 1. 将即将检 ...

  6. 【大数据之数据仓库】安装部署GreenPlum集群

    本篇将向大家介绍如何快捷的安装部署GreenPlum测试集群,大家可以跟着我一块儿实践一把^_^ 1.主机资源 申请2台网易云主机,操作系统必须是RedHat或者CentOS,配置尽量高一点.如果是s ...

  7. day08.1-Linux软件包管理

    Linux系统中的两种软件包:tar,保存内容为源码,编译后再安装:rpm,保存内容为编译后的机器码,直接安装.其中,rpm软件包由5部分构成,分别为: 第1部分是name,表示这个rpm软件包的名称 ...

  8. Django 实现上传图片功能

    很多时候我们要用到图片上传功能,如果图片一直用放在别的网站上,通过加载网址的方式来显示的话其实也挺麻烦的,我们通过使用 django-filer 这个模块实现将图片文件直接放在自己的网站上. 感兴趣的 ...

  9. go语言排序

    冒泡: package main import ( "fmt" ) func BubbleSort(arr []int) []int { // 改进的冒泡排序 num := len ...

  10. MySQL索引的索引长度问题

    转自:http://samyubw.blog.51cto.com/978243/223773 MySQL的每个单表中所创建的索引长度是有限制的,且对不同存储引擎下的表有不同的限制. 在MyISAM表中 ...