问题
I have an app in Angular 2 (2.4.1) and a server with the following:
Front-end runs on localhost:8081 and has:
node v6.17.1
npm  v3.10.10
Among devDependencies in package.json:
"devDependencies": {
    ...,
    "typescript": "2.1.1",
    "webpack": "1.13.3",
    "webpack-dev-server": "1.16.2",
    ...
}
"scripts": {
    "webpack": "webpack",
    "server": "npm run server:dev",
    "serverprod": "npm run server:prod",
    "server:dev": "webpack-dev-server -d --config config/webpack.develop.js --inline --progress --profile --colors --watch --display-error-details --display-cached --content-base src/",
    "server:prod": "webpack-dev-server -d --config config/webpack.prod.js --inline --progress --profile --colors --watch --display-error-details --display-cached --content-base src/",
    "server:dev:hmr": "npm run server:dev -- --hot",
    "start": "npm run server",
    ...
}
In webpack.config.js:
 devServer: {
        headers: {"Access-Control-Allow-Origin": "*"},
        proxy: {
            '/api': {
                target: 'http://localhost:8080',
                secure: false,
                changeOrigin: true
            }
        },
        port: METADATA.port, //8081
        host: METADATA.host, //localhost
        historyApiFallback: true,
        watchOptions: {
            aggregateTimeout: 300,
            poll: 1000
        },
        outputPath: helpers.root('dist'),
        stats: 'errors-only', // hide all the verbose info
    },
And I call API as:
export class Api {
    constructor(protected http: Http) {
    }
    public call() {
        ...
        http.post("/api", requestBody, {headers: headers})
            .map(...
    }
}
My server is on localhost:8080 and the endpoint I am trying to reach is on localhost:8080/api
Now, when I start the app with npm start I can see in logs this:
...
70% 3/3 build modules[HPM] Proxy created: /api  ->  http://localhost:8080
 http://localhost:8081/
webpack result is served from /home/
...
And when the API is called I can see in browser console this:
zone.js:1561 POST http://localhost:8081/api 404 (Not Found)
Meaning, that it does not proxy the request to port 8080, as I want it to, but instead tries to reach the API on port 8081 and fails.
How do I make it proxy the request?
I tried t configure it with "/api*", "/api/*", "/api**", "/api/**", it does not change the behavior. The app does not use "ng", does not have angular.json, so other approaches to proxying are not possible as I understand.
Could it be the "zone.js" issue?
Why does it write the http://localhost:8081/ after Proxy created: /api  ->  http://localhost:8080 when starting the app, could it mean overriding proxy target address?
来源:https://stackoverflow.com/questions/64681061/how-to-make-proxy-work-on-angular-2-with-webpack-dev-server-configuration