when I import HttpClient
to call my own written node.js API, there are some issues with the settings of the URL.
for example:
import { HttpClient, HttpHeaders } from '@angular/common/http';
export class myComponent implements OnInit {
constructor(
private http: HttpClient,
) {}
ngOnInit(): void {
this.http.get('http://127.0.0.1:3000/getData/theme').subscribe(data => {
});
});
}
//angular default port 4200,
//node.js default port 3000,
when I set this.http.get('/getData/theme')
the get
will be call http://127.0.0.1:4200
, this is wrong.
if I set this.http.get('http://127.0.0.1:3000/getData/theme')
for local development it works. but, when ng build
setting to actual server, it can't connect properly.
the console:
GET http://127.0.0.1:3000/getData/theme
net::ERR_CONNECTION_REFUSED
GET http://localhost:3000/structureData/themeData
net::ERR_CONNECTION_REFUSED
How can I set the correct URL to allow it to meet both online and local development status?
angular-cli server - how to proxy API requests to another server?
I set the package.json:
"start": "ng serve --proxy-config proxy.conf.json"
and
proxy.conf.json
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}
it's not working:
this.http.get('/getData/theme')
GET http://localhost:4200/getData/theme 404 (Not Found)
or
this.http.get('/api/getData/theme')
GET http://localhost:4200/api/getData/theme 404 (Not Found)
The pathRewrite proxy configuration option lets you rewrite the URL path at run time.
I think that happens because you missed the `changeOrigin' attribute.
I have different proxy.config.json files for local and production and it's working. I leave here an example.
Note: I use pathRewrite
to remove that string from the url. So if I request http://localhost:4200/client-api/stores it redirects to https://www.your-web.com/api/stores
"/client-api/*": {
"target": "https://www.your-web.com/api",
"pathRewrite": { "^/client-api": "" },
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
"/client-api/*": {
"target": "http://localhost:22222",
"pathRewrite": { "^/client-api": "" },
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
In angular.json use the proxy config files. You can do it in package.json too, but I prefer this way.
...
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "app:build",
"proxyConfig": "src/proxy-local.conf.json"
},
"configurations": {
"production": {
"browserTarget": "app:build:production",
"proxyConfig": "src/proxy-prod.conf.json"
},
}
},
...
If you run ng serve
, the application will use the local proxy. Use ng serve --prod
for production.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With