The Java REST call to retrieve the URL encountered an error with code net::ERR

I have written a REST call as shown below

authenticateUser(username: string, password: string) {
    debugger;
    let params = new HttpParams();
    params = params.append('username', username);
    params = params.append('password', password);
    return this.http.get(`http://localhost:8080/api/v1/basicauth?`,{params},
      ).pipe(map((res) => {
        this.username = username;
        this.password = password;
      }));
  }

On the Spring Boot side, I am using @RequestParams as follows

@GetMapping(path = "/basicauth")
    public AuthenticationBean getAuthenticatedUser(@RequestParam(name = "username") String username,@RequestParam(name = "password") String password) {
        String status = authenticationService.isUserAuthenticated(username, password);
             return new AuthenticationBean("You are not authenticated");
    }

I encountered an error like

![this ]1

Please assist me with this. Thank you:)

Answer №1

To utilize the built-in proxy options offered by the Angular development server, you can refer to the official documentation for detailed instructions.

To set up the proxy configuration, create a 'proxy.config.json' file in the 'src' folder with the following contents:

src/proxy.config.json

{
    "/api": {
        "target": "http://localhost:8080",
        "secure": false,
        "changeOrigin": true
    }
}

In your AuthenticationService file, adjust your HTTP call as shown below:

this.http.get<any>('/api/v1/basicauth', { params }).subscribe();

To run your Angular application with the proxy configuration, use the command:

ng serve --proxy-config src/proxy.config.json

AN ALTERNATE APPROACH

angular.json

...
"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.config.json"
    },
...

With this setup, you can simply use the ng serve command without the need for the '--proxy-config' flag.

Note

  1. You can now access any endpoint from your localhost:8080 server without specifying the hostname as demonstrated above, but remember that this is applicable only in the Dev environment/workflow.

  2. In higher environments like Production, it's essential to host your Angular application on the same domain as the backend server to prevent CORS errors. However, there are other methods available to address CORS issues.

  3. Based on your code snippet, you don't have to manually append '?' at the end of the URL as HttpClient will handle this automatically when you provide the params object.

We hope these instructions prove helpful. Happy coding and cheers!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving values from an array in a JSON response using Angular 4

How can I access the SubjectCode field in an array at a table using Angular 4? When trying to do so, I receive the error message: "[Error trying to diff '[object Object]'. Only arrays and iterables are allowed]". Here is the Json Response: { ...

WebStorm disregards tsconfig compiler directives when working with Angular applications

My project structure was created using angular-cli, which includes a root tsconfig.json, src/tsconfig.app.json, and src/tsconfig.spec.json. Despite having the noImplicitAny and strict options enabled in the root configuration, I do not receive error notifi ...

Rebuilding a Component's Template in Angular 2

In an ideal scenario, I would prefer to reload or rerender the template of my component. However, if there is a more efficient method available, I am open to implementing it. Desired Outcome: I have a menu component for which I need to dynamically add a ...

I am in search of a SWT file chooser dialog that includes an auto-suggestion combo feature

I am looking for a SWT file chooser dialog with an auto-suggestion combo feature. For example, when the user inputs "C:\" in the combo area, all subdirectories within drive C should be displayed. Similarly, if the user types "C:\Pr", only folders ...

Navigating with Angular 2 [routerLink] while including route parameters

Currently, I am working on developing an application using angular 2. As part of this project, I am trying to pass parameters to the [routerLink] tag in order to create a link structure like the following: <a href="/auth/signup?cell=1654654654">< ...

Steps for bypassing the authentication popup in Chrome browser during the execution of a Selenium script

click here for image descriptionWhen I try to log in with the first URL (as shown in the image), it takes me to another URL where I have to input my credentials. However, before reaching that page, a browser-generated pop-up appears that cannot be located ...

Generate a customizable form by utilizing a JSON file as a template. The JSON file can be easily modified by clicking a button, allowing for real-time

My goal is to develop a dynamic form using the guide provided at https://angular.io/guide/dynamic-form. I am utilizing two JSON files, namely sbb.json and gx.json. The initial creation of the form from the JSON file works flawlessly. However, I encountered ...

Using Angular 2 to inject a service within another service

In my application, I have customized the Angular Http class by implementing our own version with additional headers. export class Secure_Http extends Http { private getJwtUrl = environment.employerApiUrl + '/getJwt'; private refreshJwtUr ...

retrieve an archive file from the maven repository and save it to a designated folder on your

What is the correct way to download a jar file from the central repository to a specific local directory using Maven 3.04? I attempted to use the following command: mvn dependency:get -X -DrepoUrl={url} -Dartifact=groupId:artifactId:LATEST -DoutputDirect ...

Exploring Tailwind's flexibility with custom color schemes

I'm attempting to generate unique hex colors for my React/TypeScript application with Tailwind. Why isn't the background color updating based on the color variable value? Check out my code snippet below: import React, { useState } from &apo ...

Error: A SQLite Exception has occurred within the Android database, displaying a SQLite

I am working on developing an application that will display all phone numbers from received calls. To store these numbers in tables, I have utilized SQLite. Below are the classes I have created for this purpose. logcat 11-09 01:18:04.002 3027-3027/nischa ...

Guide on integrating a plain Service/Provider into nest.js

I recently created a basic TypeScript class in nest.js called JwtTokenService.js. // JwtTokenService.js import { Injectable, Optional } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { JwtPayload } from ' ...

Tips for positioning a GIF at the center of a Live Wallpaper

I am currently working on developing a live wallpaper that features a gif image stored in the raw directory. My main challenge is centering the gif image on the screen regardless of the device being used. I understand the logic behind why the image is appe ...

Access PDF document in a fresh tab

How can I open a PDF file in a new tab using Angular 6? I have tried the following implementation: Rest controller: @RestController @RequestMapping("/downloads") public class DownloadsController { private static final String EXTERNAL_FILE_PATH = "/U ...

Having trouble getting the ValidatorPipe to function properly in my nest.js application

Issue Description There is an issue with the current behavior where initializing a validation pipe for a request body does not reject invalid types as expected. Desired Outcome The expected behavior should be that when a user provides a value that does n ...

Generate and execute a dynamic Java or Scala method body in real-time

Imagine having the following Interface declared in Java: public interface DynamicMethod { String execute(); } Is it feasible to create an Object dynamically at runtime that adheres to the above interface, allowing me to inject custom code into its ex ...

Develop a module using the Angular plugin within the Eclipse IDE

I am currently new to Angular and following the Angular Get Started Tutorial (https://angular.io/guide/quickstart). I am using the angular cli plugin in Eclipse. As I reached the 7th part of the tutorial, I am required to create a new module with the comm ...

Challenges encountered when implementing a personal library in a separate project

After updating a library I own, I seem to have encountered an issue when trying to use it in another project. However, the reason for this problem eludes me. A multitude of error logs with a similar theme are appearing: ERROR in ./node_modules/@company-na ...

Creating test case records in Excel format using the Selenium IDE

Currently, I document website actions using Selenium IDE and then manually transfer the test cases to an Excel sheet. Is there a more efficient way to directly export the output to an Excel file? I understand that exporting from IDE to Excel is not suppo ...

I encounter difficulties in executing a request through ReactJS, as the header cannot be properly composed

const fetchData = async () => { try { const response = await axios.get('http://localhost:8080/omp/patients', { headers: {authorization: 'Bearer ' + token}}); this.state = response.data; } catch (ex) { ...