Saturday 8 April 2017

Have express server static assets from another http server (webpack dev server)

Backend beginner here. I have a node/express rest api from which, in development, I would like to serve an angular2.x/4.x web app from the webpack-dev-server running on port 3000.

I have the following code which works well enough for index.html and the javascript bundles, but does not work for images:

app.get('*', (req: express.Request, res: express.Response) => {
  isProd ? useBuild(res) : useDevServer(req, res);
});

function useDevServer (req: express.Request, res: express.Response): void {
  const options: any = {
    path: sanitizeWebAppPaths(req.path),
    port: 3000
  };

  http.get(options, (targetRes: http.IncomingMessage) => {
    let rawData: string = '';

    targetRes.on('data', (chunk) => {
      rawData += chunk;
    });
    targetRes.on('end', () => {
      res.send(rawData);
    });
  }).on('error', e => {
    console.warn(`\nGot error: ${e.message}\n`);
  });
}

The code above returns images 200 but in the wrong format, I suspect, because I can't see the response in the browser network tab and the response headers include Content-Type:text/html; charset=utf-8. Manually setting that header to image/jpeg does not seem to work.

Probably I'm thinking about this the wrong way, would be happy for enlightenment :)



via Manningham

No comments:

Post a Comment