DEV Community

Roelof Jan Elsinga
Roelof Jan Elsinga

Posted on • Originally published at roelofjanelsinga.com on

1

Proxy API calls to your server during Angular development

"Angular logo"

Proxy API calls to your server during Angular development

When you're developing an Angular application, you'll most likely use "ng serve" to display your application. When you're trying to request data through API calls to "/api/some/resource" you get a 404 response. But why? Well Angular sends the API request to http://localhost:4200/api/some/resource. Because you're not specifying a domain in your services, just a path, Angular will send the request to the current domain, which is fine for development, but will break in development.

This is where the built-in proxy comes into play. When you're using "ng serve", you're serving the application at http://localhost:4200. This means the services will call the API at http://localhost:4200/api/some/resource, however, your API server doesn't exist at that URL and returns a 404 for everything. Your API server is served at something like http://localhost:8000/api/some/resource. By creating this proxy, the development server accepts the requests at port 4200 and sends them to port 8000 behind the scenes. So now you get your data instead of a 404.

The code for this to work

This is the config you would be using for the situation I painted here:

{
  "/api": {
    "target": "http://localhost:8000",
    "secure": false
  }
}
Enter fullscreen mode Exit fullscreen mode

This config should be placed in a new file called: "proxy.conf.json" and you should place this in the src folder of your Angular project. Next, you need to point to this file in "angular.json". Open the file and search for the "serve" section. Here you can add a "proxyConfig" key to the options. You should end up with something similar to this:

"serve": {
    "builder": "...",
    "options": {
        "proxyConfig": "src/proxy.conf.json"
    }
}
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay