节点/ Express-使用API​​ JSON响应来(服务器端)呈现应用

时间:2019-04-07 18:26:18

标签: javascript node.js api express express-handlebars

序言:我是Web开发人员的新手,所以对于兽医来说,这也许是一个非常基本的问题。

我正在为此基本应用程序使用MVC架构模式。我有模型(MongoDB),视图(Express Handlebars)和控制器(接受req,res,next和return promises的函数(.then> JSON返回,.catch> error返回)。我将进行路由路径要求到达其在控制器中相应的api端点。

当我纯粹从事以JSON为资源的API调用时,这很有意义(对吗?)。但是,我也想调用这些api端点>获取其res.json>并使用它使用Handlebars渲染HTML。做到这一点的最佳方法是什么?我可以创建相同的控制器,而不是用JSON代替,而可以进行渲染(“ html视图”,res.json)。但这似乎是我在重复相同的代码,只是为了更改响应(返回JSON或呈现JSON)。

希望我有道理,如果没有,请告诉我。请告知。

p.s。尝试为我提供ELI5的功能。 (:

编辑:

//Model Example
const Schema = require('mongoose').Schema;

const testSchema = new Schema({
    testText: { type: String, required: true },
});

const Test = mongoose.model('Test', testSchema);

module.exports = Test;


//Controller Example
const model = require('../models');

module.exports = {
    getAll: function(req, res, next) {
        model.Test.find(req.query)
            .then((testItems) => {
                !testItems.length
                    ? res.status(404).json({ message: 'No Test Item Found' })
                    : res.status(200).json(testItems);
            })
            .catch((err) => next(err));
    },
};

//Route Example
const router = require('express').Router(),
    controller = require('../controllers');

router.get('/', controller.getAll);

module.exports = router;

我希望端点返回JSON,并以某种方式管理是否渲染(如果请求来自浏览器)还是保留JSON(例如从Postman或API Web URL调用)而无需重复代码。我试图不以99%的代码相同来创建两个endpoitns,唯一的区别是.then> res.status(200).json(testItems); vs .then> res.status(200).render('testPage',{testItems})。

2 个答案:

答案 0 :(得分:0)

对于邮递员,您可以检查postman-tokenreq.headers的存在,然后可以相应地进行渲染,如下所示:

req.headers['postman-token'] ? res.json({ /* json */ }) : render('view', {/ * json */});

答案 1 :(得分:0)

如果您想使用checking postman token,则可以使用类似于method1的东西。

如果您想在这种情况下使用查询参数进行检查,甚至可以从浏览器获得json响应或html以便将来使用,并且它不依赖邮递员,则可以使用类似于以下内容的method2例子。

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
const port = 5000



app.get('/method1', (req, res) => {
  const isJSONResp = req.headers['postman-token']
  const resp = { status: "hello" }
  if (isJSONResp) {
    res.json(resp)
  } else {
    res.render('some.html', resp)
  }
})

app.get('/method2', (req, res) => {
  const params = req.params
  const resp = { status: "hello" }
  if (params.resp === 'json') {
    res.json(resp)
  } else {
    res.render('some.html', resp)
  }
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))