'Angular Proxy in root level
I have an Angular application and a landing page written in jQuery.
I want to serve the landing page every time the request is on the root of http://mywebsite.com. Anything else, let's say http://mywebsite.com/otherpage, I want to serve the Angular application.
With nginx (production), this is fairly easy.
When developing Angular, we can easily proxy other requests, like /api, with --proxy-config proxy.config.json CLI option.
The problem I'm getting is with the root level.
What am I doing wrong? Can't I proxy the root level?
Angular docs tells us to go to Webpack dev-server docs, but still I couldn't figure out how to do it.
My proxy.config.json is like the following:
{
"/api/*": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug"
},
"/": {
"index": "",
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug"
}
}
Solution 1:[1]
It looks like it was a conflict with the root level after all.
Changing to other level, I could make it work.
The documentation is not explanatory on this.
Solution 2:[2]
It works if you set devServer.index to a falsy value.
https://webpack.js.org/configuration/dev-server/#devserver-proxy
Note that requests to root won't be proxied by default. To enable root proxying, the
devServer.indexoption should be specified as a falsy value:
module.exports = {
//...
devServer: {
index: '', // specify to enable root proxying
host: '...',
contentBase: '...',
proxy: {
context: () => true,
target: 'http://localhost:1234'
}
}
};
Solution 3:[3]
I got this to work as follows:
In angular.json:
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./my-custom-webpack.config.js"
},
...
"serve": {
"builder": "@angular-builders/custom-webpack:dev-server",
"options": {
"proxyConfig": "webpack-proxy.conf.js",
...
In my-custom-webpack.config.js:
module.exports = {
...
devServer: {
index: '' // Allows us to proxy the root URL
}
}
In webpack-proxy.conf.js
const PROXY_CONFIG = [{
context: [
'/'
],
target: 'http://proxy-to-url',
bypass: function(request) {
// proxy the root URL, plus "/api/*" - otherwise serve using Angular
return /^\/(api\/.*)?$/.test(request.url) ? null : '/index.html';
},
secure: false
}];
module.exports = PROXY_CONFIG;
(Needs @angular-builders/custom-webpack installed: npm i -D @angular-builders/custom-webpack)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | MicMro |
| Solution 3 |
