简体   繁体   English

使用 req,res 参数调用函数

[英]Call a function with req,res params

I'm making an API on NodeJS with Express.我正在使用 Express 在 NodeJS 上制作 API。 I have a function in the schema Products who return a product by id.我在架构 Products 中有一个函数,它按 id 返回一个产品。 The signature of this function is like this:这个函数的签名是这样的:

let getProductsById = (req, res) => {
    let id = req.params.id;
    Producto.findById(id)
        .populate('categoria')
        .populate('marca')
        .exec((err, producto) => {
            if (err) {
                return res.status(500).json({
                    ok: false,
                    error: err
                });
            }
            if (!producto) {
                return res.status(400).json({
                    ok: false,
                    error: {
                        message: 'Producto no encontrado'
                    }
                });
            }
            productoResponse = {
                _id: producto._id,
                codigo: producto.codigo,
                descripcion: producto.descripcion,
                nombre: producto.nombre,
                precioCosto: producto.precioCosto,
                precioVenta: producto.precioVenta,
                categoria: {
                    _id: producto.categoria._id,
                    nombre: producto.categoria.nombre
                },
                marca: {
                    _id: producto.marca._id,
                    nombre: producto.marca.nombre
                }
            }
            res.json({
                ok: true,
                producto: productoResponse
            });
        });
}

If you don't want to read the entire function, in resume this return a object with some info in it.如果您不想阅读整个函数,请在恢复中返回一个包含一些信息的对象。

I call this function in the router like this:我在路由器中调用这个函数是这样的:

app.get('/producto/:id', function(req, res) {
    getProductsById(req, res);
});

This works fine, but I want in another schema (Cart) to call this function to recive a product.这工作正常,但我想在另一个模式(购物车)中调用此函数来接收产品。 In the service of Cart I have this function:在 Cart 的服务中,我有这个功能:

let addCart = (req, res) => {
    let body = req.body;
    let cart = new Cart({
        user: body.user,
        products: body.products,
        pay: body.pay,
        address: body.address,
        phone: body.phone,
        moreInfo: body.moreInfo,
        total: body.total
    });
    cart.products.forEach(product => {
        console.log(product._id);
        req.params.id = product._id;
        let productX = getProductsById(req,res);
    });
}

But this don't work, I have a error that says:但这不起作用,我有一个错误说:

events.js:288
      throw er; // Unhandled 'error' event
      ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (C:\Users\Nacho\Desktop\node\07-restserver\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\Nacho\Desktop\node\07-restserver\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\Nacho\Desktop\node\07-restserver\node_modules\express\lib\response.js:267:15)
    at C:\Users\Nacho\Desktop\node\07-restserver\server\services\productService.js:57:40
    at C:\Users\Nacho\Desktop\node\07-restserver\node_modules\mongoose\lib\model.js:4832:16
    at C:\Users\Nacho\Desktop\node\07-restserver\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16
    at C:\Users\Nacho\Desktop\node\07-restserver\node_modules\mongoose\lib\model.js:4855:21
    at C:\Users\Nacho\Desktop\node\07-restserver\node_modules\mongoose\lib\query.js:4407:11
    at C:\Users\Nacho\Desktop\node\07-restserver\node_modules\kareem\index.js:135:16
    at processTicksAndRejections (internal/process/task_queues.js:79:11)
Emitted 'error' event on Function instance at:
    at C:\Users\Nacho\Desktop\node\07-restserver\node_modules\mongoose\lib\model.js:4834:13
    at C:\Users\Nacho\Desktop\node\07-restserver\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16
    [... lines matching original stack trace ...]
    at processTicksAndRejections (internal/process/task_queues.js:79:11) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

How can I resolve this problem?我该如何解决这个问题? Ty.泰。

I resolve doing this way (don't follow my steps is bad and I need to restructure the code)我决定这样做(不按照我的步骤是不好的,我需要重组代码)

carrito.productos.forEach(producto => {
        console.log(producto._id);
        let id = producto._id;
        Producto.findById(id)
        .exec((err, productoObtenido) => {
            if (err) {
                return false;
            }
            if (!productoObtenido) {
                return false;
            }
            producto.precioVenta = productoObtenido.precioVenta;
        });
    });

Problem is here问题在这里

cart.products.forEach(product => {
    console.log(product._id);
    req.params.id = product._id;
    let productX = getProductsById(req,res);
});

So you're calling res.send multiple time from getProductsById所以你从getProductsById多次调用res.send

They express refuse it.他们表示拒绝。

I think you should restructure your app.我认为你应该重组你的应用程序。 Move your actual business logic on a layer behind the request and response handling.将您的实际业务逻辑移到请求和响应处理之后的层上。 That way you can reuse services/functionality without passing the request and response objects around, which makes your code way harder to write and to understand.这样你就可以重用服务/功能而无需传递请求和响应对象,这会使你的代码更难编写和理解。

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

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