Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack-dev-server with backend api

I am using webpack-dev-server for an angularjs app, I start it from a task in package.json like this:

  "scripts": {
    "start-api": "node api/server.js",
    "dev": "webpack-dev-server --env dev --history-api-fallback --inline --progress --port 5000",
    "start": "npm run dev"
  },

I have a backend api server that uses koa and is running on the same port:

const koa = require('koa');

app.listen(5000);

module.exports.app;

When the koa server is started, it intercepts all requests and I cannot browse to the angular browser app.

Should I be serving everything from koa or is there a way to have the two working together?

like image 702
dagda1 Avatar asked Feb 21 '16 16:02

dagda1


People also ask

Is webpack needed for backend?

It's not necessary at all. I'm not saying you can't or shouldn't set up a webpack-dev-server to develop your back-end code locally. But you definitely don't need to bundle your backend code on your build process. webpack bundles are meant for the browser.

What is webpack-dev-server used for?

webpack-dev-server is Webpack's officially supported CLI-based tool for starting a static server for your assets. While you don't need any CLI tools to use Webpack, webpack-dev-server gives you a single command that starts a static server with built-in live reload.

What is Contentbase in webpack?

Exists only in webpack-dev-server. It's only needed if you want to serve static files. For example, you want a folder of mp4 vacation movies to be available for the app, but you don't want to run them through the bundle, because that would be silly.


1 Answers

Yes, you can use webpack-dev-server with your own backend API. There are two ways to do this:

First, you can configure the dev-server to use a proxy. This is the solution I use and it works well for me. My configuration looks something like this:

proxy: {
  "/api/*": {
    target: "http://localhost:8080"
  }
}

This configuration ensures that all requests beginning with "/api" are sent to the backend API server (running on localhost:8080 in this case), rather than the dev-server. Optionally, if you need to, you can bypass the proxy with a function, like so:

proxy: {
  "/api/*": {
    target: "http://localhost:8080",
    bypass(req, res) {
      return (/* some condition */) ? '/index.html' : false;
    }
  }
}

But I have never needed to use this, since the "/api/*" key is all I need to ensure each request is sent to the right server.

Importantly, you should have the two servers running on different ports. I usually use 8080 for my backend, and 9090 for the dev-server.

like image 67
McMath Avatar answered Oct 17 '22 16:10

McMath