javascript – 在expressjs中创建模型

我有一个快速应用程序,从外部API获取其数据

api.com/companies (GET, POST)
api.com/companies/id (GET, PUT)

我想创建一个模型来使代码更容易维护,因为你可以看到我在这里重复了很多代码.

router.get('/companies', function(req, res, next) {

    http.get({
        host: 'http://api.com',
        path: '/companies'
    }, function(response) {
        var body = '';
        response.on('data', function(d) {
            body += d;
        });
    });

    res.render('companies', {data: body});
});

router.get('/companies/:id', function(req, res, next) {

    http.get({
        host: 'http://api.com',
        path: '/companies/' + req.params.id
    }, function(response) {
        var body = '';
        response.on('data', function(d) {
            body += d;
        });
    });

    res.render('company', {data: body});
});

我怎样才能做到这一点?

解决方法:

首先:
http.get是异步的.经验法则:当您看到回调时,您正在处理异步函数.您无法判断,当您使用res.render终止请求时,是否将完成http.get()及其回调.
这意味着res.render总是需要在回调中发生.

我在这个例子中使用了ES6语法.

// request (https://github.com/request/request) is a module worthwhile installing. 
const request = require('request');
// Note the ? after id - this is a conditional parameter
router.get('/companies/:id?', (req, res, next) => {

    // Init some variables
    let url = ''; 
    let template = ''

    // Distinguish between the two types of requests we want to handle
    if(req.params.id) {
        url = 'http://api.com/companies/' + req.params.id;
        template = 'company';
     } else {
        url = 'http://api.com/companies';
        template = 'companies';
     }

    request.get(url, (err, response, body) => {

        // Terminate the request and pass the error on
        // it will be handled by express error hander then
        if(err) return next(err);
        // Maybe also check for response.statusCode === 200

        // Finally terminate the request
        res.render(template, {data: body})
    });

});

关于你的“模特”问题.
我宁愿称它们为“服务”,因为模型是一些数据集合.服务是逻辑的集合.

要创建公司服务模块,请执行以下操作:

// File companyService.js
const request = require('request');

// This is just one of many ways to encapsulate logic in JavaScript (e.g. classes)
// Pass in a config that contains your service base URIs
module.exports = function companyService(config) {
    return {
        getCompanies: (cb) => {
            request.get(config.endpoints.company.many, (err, response, body) => {
                return cb(err, body);
            });
        },
        getCompany: (cb) => {
            request.get(config.endpoints.company.one, (err, response, body) => {
                return cb(err, body);
            });
        },
    }
};


// Use this module like
const config = require('./path/to/config');
const companyService = require('./companyService')(config);

// In a route
companyService.getCompanies((err, body) => {
    if(err) return next(err);

    res.render(/*...*/)
});

原文地址:https://codeday.me/bug/20190519/1134322.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


根据官网 入门 express
java叫接口control什么的app.get.post等等都是请求方式我们可以在游览器输入localhost端口/或者在Apifox里面写。
为了前端丢进去的时候可以直接判断中间件就是经过了这个就会被使用可以做一些自己的数据处理什么的。
Express 文件的上传和下载
运行命令下载app.js 增加中间件。
基本模板来的 后面用后就有什么加什么都行。
此篇完成 增删 刷新文件 的基本操作
最基本的创建 以及 添加了其他的一些插件 登录接口和四个接口
由于每个接口都要放就很麻烦 所以做个中间件
1importre234defstrip_operate(exp):#合并多余的操作符5exp=exp.replace("+-","-")6exp=exp.replace("--","+")7returnexp8910defcal_exp_son(exp_son):#计算两数的乘除11if&
 socket.html<script>//高级api不兼容socket.io//http单向的,socket是双向的,传输都靠tcpletsocket=newWebSocket('ws://localhost:3000')socket.onopen=()=>{//多个页面通信就是先发给服务器,服务器再发给另一个页面socket.send('我
M模式:类,表示数据的应用程序和使用验证逻辑以强制实施针对这些数据的业务规则。V视图:应用程序使用动态生成HTML响应的模板文件。C控制器:处理传入的浏览器请求的类中检索模型数据,然后指定将响应返回到浏览器的视图模板。简单练习: 1、添加ControllerHelloWorldControlle
在Node开发中免不了要使用框架,比如express、koa、koa2拿使用的最多的express来举例子开发中肯定会用到很多类似于下面的这种代码varexpress=require('express');varapp=express();app.listen(3000,function(){console.log('listen3000...');});app.use(middle
node的http创建服务与利用Express框架有何不同原生http模块与使用express框架对比:consthttp=require("http");letserver=http.createServer(function(req,res){//服务器收到浏览器web请求后,打印一句话console.log("recvreqfrombrowser");
编辑nginx文件vi/usr/local/etcginxginx.confnginx配置如下,配置后需重启nginxnginx-sreloadlocation~.*\.json{roothtml;add_header"Access-Control-Allow-Origin""*";}前端index.html<script>fetch('http://localhost:12
constexpress=require('express')constapp=express()//步骤的拆解constresult=express.static('./views')app.use(result)//再次托管一下样式表的资源目录app.use('/css',express.static('./css'))//托管JS文件目录app.use('/js&#
问题描述:最近在做毕设,express里边的中间件(body-parser)失效,req.body获取不到任何值,req.query能获取到值。一开始加body-parser中间件是有用的,直到昨天加了token之后,body-parser失效。试着把token去掉,无济于事,也不是这个问题,也有说版本对不上的,换了中间件的引入方法,还是没用!!! 后
express官网:---->传送门 expressexpress框架有许多功能,比如路由配置,中间件,对于想配置服务器的前端来说,非常便捷自从node发展之后,基于nodejs的开发框架也不断涌现出来,express就是其中之一,最近简单的写了点express框架的简单的处理请求的demo首先是安装express模块npminstall
目录问题: 操作:Win+S按键,输入“事件查看器”问题详情:模块DLLC:\ProgramFiles(x86)\IISExpress\aspnetcore.dll未能加载。返回的数据为错误信息。问题:  操作:Win+S按键,输入“事件查看器” 问题详情:模块DLLC:\ProgramFiles(x86)\IISExpress\aspnetcore.dll
//获取阿里云市场,快递物流记录https://market.aliyun.com/products/56928004/cmapi022273.html?spm=5176.2020520132.101.26.61f97218v18GBF#sku=yuncode1627300000//get_express_log(self::$config['web']['aliyun_AppCode']阿里云市场AppCode,缓存秒数如300秒,'快递公司代