Can I use 'res.sendFile' and 'res.json' together?

后端 未结 1 1334
梦如初夏
梦如初夏 2021-01-06 02:44

Currently I\'m using a controller within my Express app to handle routing. When a certain route is hit I call pagesController.showPlayer which serves my i

相关标签:
1条回答
  • 2021-01-06 02:48

    The res.json() represents the HTTP response that an Express app sends when it gets an HTTP request. On the other hand, res.sendFile() transfers the file at the given path.

    In both cases, the flow is essentially transferred to client who might have made the request.

    So no, you cannot use res.sendFile and res.json together.

    However, you do have few workarounds to achieve the desired goal:

    res.sendFile have the following signature:

    res.sendFile(path [, options] [, fn])
    

    Where path must be an absolute path of the file(Unless the root option is set in the options object).

    In options, you can specify the object containing HTTP headers to serve with the file.

    example:

      var options = {
        headers: {
            'x-timestamp': Date.now(),
            'x-sent': true,
            'name': 'MattDionis',
            'origin':'stackoverflow' 
        }
      };
    
    res.sendFile(path.join(__dirname, '../assets', 'index.html'), options);
    

    Thats really the closest you can do to achieve the desired task. There are other options too..

    • like setting content in a cookie(but that'll be a part of each subsequent req/res cycle), or
    • sending just a json response (with res.json) and manage routing at client side(while nodejs will serve as an API end), or
    • set res.locals object that contain variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any)

    Hope it Helps!

    0 讨论(0)
提交回复
热议问题