简体   繁体   English

返回一个 res.json 并在其他路由器中使用 res.render 获取它

[英]Return a res.json and get it with res.render in other router

Im working to return a JSON from the router "/api/product" but render the answer with hbs in the router "/product".我正在努力从路由器“/api/product”返回一个 JSON,但在路由器“/product”中使用 hbs 呈现答案。 The code works, but is it correct?代码有效,但它正确吗?

My router in this case is: '/api/product'在这种情况下,我的路由器是:'/api/product'

router.get('/', this.controlador.renderProducts);

renderProducts = async (req, res) => {
    try {
      const docs = await this.ProductsDAO.mostrarTodos();

      const productos = docs.map((p) => {
        return new ProductDTO(
          p.id,
          p.precio,
          p.stock
        );
      });

      res.status(200).json({ product:productos });
    } catch (error) {
      logger.error('Error al renderizar productos', error);
      res.status(400).send('Status: No se ha renderizar productos');
    }
  };

Is correct on server.js add this code for it? server.js 上是否正确添加此代码?

app.get('/product', new RequestViews().getProductAll)

class RequestViews {
  constructor() {
    this.url = 'http://localhost:8080/api/product';
  }

 getProductAll = (req, res, next) => {
    request.get(this.url, (err, response, body) => {
      if (err) {
        return next(err);
      }
      res.render('products', JSON.parse(body));
    });
  }

Thanks!!谢谢!!

There's no need to make internal HTTP requests within your Express app.无需在您的 Express 应用程序中发出内部 HTTP 请求。 Instead, encapsulate logic into re-usable functions.相反,将逻辑封装成可重用的函数。

For example, you can capture the mostrarTodos() and .map() in a function...例如,您可以在函数中捕获mostrarTodos().map() ...

const getProducts = async () => {
  const docs = await ProductsDAO.mostrarTodos();

  const productos = docs.map((p) => new ProductDTO(p.id, p.precio, p.stock));
};

and call that from both route handlers并从两个路由处理程序中调用它

renderProducts = async (req, res) => {
  try {
    res.status(200).json({ product: await getProducts() });
  } catch (error) {
    logger.error("Error al renderizar productos", error);
    res.status(400).send("Status: No se ha renderizar productos");
  }
};
class RequestViews {
  getProductAll = (req, res, next) => {
    getProducts()
      .then((product) => {
        res.render("products", { product });
      })
      .catch(next);
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM