的WebPack-DEV-服务器与后端API [英] webpack-dev-server with backend api

查看:403
本文介绍了的WebPack-DEV-服务器与后端API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的WebPack-DEV-服务器的angularjs应用程序,我开始从一个任务在这样的package.json:

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"
  },

我有一个使用KOA和相同的端口上运行一个后台API服务器:

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;

当KOA服务器启动时,它会拦截所有请求,我无法浏览到角浏览器应用程序。

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

我应该提供一切从KOA还是有办法有两个一起工作?

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

推荐答案

是的,你可以使用的WebPack-DEV-服务器自己的后端API。有两种方法可以做到这一点:

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

首先,你可以配置DEV-服务器使用代理。这是我使用的解决方案,它很适合我。我的配置看起来是这样的:

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"
  }
}

该配置可确保以/ API开头的所有请求都被发送到后端服务器API(本地主机上运行: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;
    }
  }
}

但我从来没有需要使用这个,因为/ API / *键是我需要确保每个请求被发送到正确的服务器。

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.

重要的是,你应该有不同的端口上运行两个服务器。我通常用8080我的后端,和9090 dev的服务器。

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

有另一种方式来做到这一点,但我与它不太熟悉。我从来没有亲自使用它,因为代理选项似乎不太复杂,它的工作原理。但是你可以读到这里 ,如果你找到的代理选项是不适合某些原因。

There is another way to do this, but I am less familiar with it. I have never used it personally, since the proxy option seems less complicated and it works. But you can read about it here, in case you find the proxy option is unsuitable for some reason.

这篇关于的WebPack-DEV-服务器与后端API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆