webpack-dev-server with backend api

半腔热情 提交于 2019-12-12 10:47:29

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35538472/webpack-dev-server-with-backend-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!