[英]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: 我正在使用webpack-dev-server作为angularjs应用程序,我从package.json中的任务开始,如下所示:
"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: 我有一个后端api服务器,它使用koa并在同一个端口上运行:
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. 当koa服务器启动时,它会拦截所有请求,我无法浏览角度浏览器应用程序。
Should I be serving everything from koa or is there a way to have the two working together? 我应该从koa服务还是有办法让两者一起工作?
Yes, you can use webpack-dev-server with your own backend API. 是的,您可以将webpack-dev-server与您自己的后端API一起使用。 There are two ways to do this: 有两种方法可以做到这一点:
First, you can configure the dev-server to use a proxy . 首先,您可以将dev-server配置为使用代理 。 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. 此配置确保以“/ api”开头的所有请求都发送到后端API服务器(在本例中为localhost:8080),而不是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. 但我从来不需要使用它,因为“/ api / *”键是我需要确保将每个请求发送到正确的服务器。
Importantly, you should have the two servers running on different ports. 重要的是,您应该让两台服务器在不同的端口上运行。 I usually use 8080 for my backend, and 9090 for the dev-server. 我通常使用8080作为后端,9090作为开发服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.