Using TypeScript in combination with Angular for implementing CORS protocol

As I try to send a request to my REST endpoint, the following code is executed:

this.http.request(path, requestOptions);

The path is set to:

http://localhost:8082/commty/cmng/users
and the requestOptions are as follows:

{
    headers: { user: "sdf", password: "sdf" }
}

An issue arises when the browser attempts to obtain CORS permission before sending the request.

Here's the CURL request the browser makes for CORS HTTP:

 curl "http://localhost:8082/commty/cmng/users" -X OPTIONS
   -H "Host: localhost:8082"
   -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
   -H "Access-Control-Request-Method: PUT"
   -H "Access-Control-Request-Headers: passwd,user"
   -H "Origin: http://localhost:3000"
   -H "Connection: keep-alive"

Although a 200-OK response is received after the CORS request, the flow gets interrupted, preventing my request from being sent.

The response content is shown below:

Object { _body: error, status: 0, ok: false, statusText: "", headers: Object, type: 3, url: null }

This is the CORSFilter.java implementation:

@Provider
public class CORSFilter implements ContainerResponseFilter
{

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException
    {   
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        responseContext.getHeaders().add("Access-Control-Max-Age", "1209600");
    }

}

However, the server responds with the following:

Object {
  _body: error,
  status: 0,
  ok: false,
  statusText: "",
  headers: Object,
  type: 3,
  url: null
}

https://i.sstatic.net/MyRzG.png

Error Message

Object {
  _body: error,
  status: 0,
  ok: false,
  statusText: "",
  headers: Object,
  type: 3,
  url: null
}

Any suggestions on resolving this issue?

Answer №1

Instead of relying on this filter, consider utilizing the @CrossOrgin annotation as an alternative. This can help avoid potential exceptions that may arise due to configuration errors with the filter.

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

Tips for ensuring the alignment of a table header and body once data has been loaded into it

I am currently developing an Angular 7 application where I am trying to populate a table with data retrieved from a web service. However, the issue I am facing is that the headers of the table do not align properly with the body content after loading data ...

Ways to shift the focus away from the current date in the Angular Material Datepicker

Is there a way to prevent the focus on today's date when utilizing Angular Material datepicker? I have attempted to include certain properties to mat-datepicker without success. Here is what I have tried: restoreFocus="false" [startAt]="null" &l ...

Tips on switching the default camera with ngx-scanner-qrcode library in Angular

In my current project, I am utilizing the ngx-sanner-qrcode library for QRCode scanning. However, I am interested in changing the default camera from front to back in order to enhance the user experience. I assumed that I could change the default camera b ...

Customize the appearance of the Material UI expansion panel when it is in its expanded

Is there a way to customize the height of an expanded expansion panel summary? Specifically, I am looking to remove the min-height property and set the summary panel's height to 40px instead of the default 64px. I have attempted to make this change in ...

Error with the type of CanvasGradient in the NPM package for converting text to image

I attempted to generate an image using a specific text by utilizing npm's text-to-image package, but encountered an error during typescript compilation. The errors I encountered upon running the typescript compilation command are related to files with ...

Having trouble retrieving the file using the MS Graph API, however, it is successfully accessible through Graph Explorer

User B received an excel file shared from User A's Onedrive, whether it is in the personal folder or business OneDrive. Accessing it through regular means such as a link works fine for user B. Running the call in MS Graph Explorer produces the expect ...

A method for modifying the key within a nested array object and then outputting the updated array object

Suppose I have an array called arr1 and an object named arr2 containing a nested array called config. If the key in the object from arr1 matches with an id within the nested config and further within the questions array, then replace that key (in the arr1 ...

Angular 2 404 Error persists despite successful retrieval of data from Oracle database using Backend Nodejs URL entered directly into the browser

Recently, I've been working on displaying data in my Angular frontend that is fetched from an Oracle DB connected to my Node backend. When I access the physical API link, the data appears and is displayed in the backend console.log. I'm wonderin ...

When creating a new instance of the Date object in Javascript, the constructor will output a date that is

In my project using TypeScript (Angular 5), I encountered the following scenario: let date = new Date(2018, 8, 17, 14, 0); The expected output should be "Fri Aug 17 2018 14:00:00 GMT-0400 (Eastern Daylight Time)", but instead, it is returning: Mon Sep ...

Get a specific attribute of an object instead of directly accessing it

Is there a way to retrieve a specific object property in my checkForUrgentEvents method without referencing it directly? I attempted using Object.hasOwnProperty but it didn't work due to the deep nesting of the object. private checkForUrgentEvents(ur ...

Angular 4 yields an undefined result

I'm currently working on this piece of code and I need help figuring out how to return the value of rowData in this scenario. private createRowData() { const rowData: any[] = []; this.http .get(`/assets/json/payment.json`) .toPromise() .then(r ...

Retrieve the Angular Firebase Document and send it back

I have a question related to retrieving a Document from my FireDatabase. The model I am using is for a user, which looks like this: export class User { useremail: string; userid: string; username: string; constructor(usermail: string, use ...

How to use TypeScript to print a blob (PDF) in Internet Explorer or Microsoft Edge?

I need to print a pdf blob using typescript. I've tried the following code, which works in Chrome but not in Edge. Code 1 (works in Chrome but prints blank in Edge) - const fileURL = URL.createObjectURL(blob); const iframe = document.createE ...

Tips for creating a webfont using SVG icons

Seeking advice on generating a webfont from SVG icons using webpack, angular2, and typescript. Any suggestions on the best way to achieve this? Struggling to find helpful information online. Please lend a hand! https://i.sstatic.net/kvClK.png The code pr ...

Troubleshooting Problem with Angular 2 Filters

Here is an example of how I am utilizing the filter: <ion-item *ngFor="let contact of contacts | isMember"> <ion-label>{{contact.name}}</ion-label> {{contact.phoneNumber}}-{{contact.isMember}} </ion-ite ...

Issues with Vercel's JavaScript Environment Variables Accessibility

I am encountering an issue trying to access environment variables on Vercel using JavaScript (TypeScript). Despite setting them under /settings/environment-variables, I receive undefined when attempting to access them with process.env.TURSO_DATABASE_URL du ...

The element 'x' is implicitly bound with a type of 'any'

I've been exploring the world of Nextjs and TypeScript in an attempt to create a Navbar based on a tutorial I found (). Although I've managed to get the menu items working locally and have implemented the underline animation that follows the mou ...

The value returned by Cypress.env() is always null

Within my cypress.config.ts file, the configuration looks like this: import { defineConfig } from "cypress"; export default defineConfig({ pageLoadTimeout: 360000, defaultCommandTimeout: 60000, env: { EMAIL: "<a href="/cdn-cgi/ ...

Attempting to retrieve backend data through an API to be displayed on the frontend

After successfully sending form data from my React front end to the server using fetch, I am struggling to make this data accessible from the front end again. Despite being able to access and utilize the data within my API function on the server side, I&ap ...

How to Retrieve a File Using Angular 2

Currently, I am trying to download a file in pdf format using Angular 2. For this purpose, I have incorporated FileSaver.js to facilitate the saving of the file as a pdf. (response) => { var mediaType = 'application/pdf'; let pdfConte ...