Angular 4 is in need of CORS support

I have a server application with CORS enabled, which works well with my AngularJS client (1.x). However, I am now upgrading to Angular 4 and encountering the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ||my-url||. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

Despite having CORS enabled on the server side, my Angular 4 client seems to be the issue according to many questions I have researched.

EDITED

I have modified my service.ts as follows:

createAuthorizationHeader(): RequestOptions {
    if (isNull(this._options)) {
      const headers = new Headers();
      headers.append('Access-Control-Allow-Origin', '*');
      headers.append('Access-Control-Allow-Headers', 'X-Requested-With, content-type');
      headers.append('Content-Type', 'application/json; charset=utf-8');
      this._options = new RequestOptions({headers: headers});
    }
    return this._options;
}

getStudies(): Observable<any> { 
    const options = this.createAuthorizationHeader();
    return this._httpService.get(this.WEB_API_URL, options)
    .map((response: Response) => console.log(response.json()))
}

NEW EDIT

It appears that there is still confusion. I have an Angular 1.x application running on the same server as the new Angular 4 application. The server has CORS properly configured. I had to make changes to the client for the Angular 1 application to work, and now I need to figure out how to do the same for Angular 4.

Answer №1

I encountered a similar problem while working with React, but managed to fix it by incorporating

https://cors-anywhere.herokuapp.com/
. Feel free to give it a shot to see if it resolves the issue.

https://cors-anywhere.herokuapp.com/
+ Your specific API URL

Answer №2

Utilize the Proxy to Backend feature offered by angular-cli

What's the Reason?

Manually adding headers to your request won't solve the issue as these headers are typically set by the server.

Your browser has a built-in security measure that requires these specific headers to be present when making requests to a different domain from your application. The browser initiates an OPTIONS request before proceeding with the original request (usually a GET request) to verify these headers.

To address this, you can adjust your server to include the necessary headers or opt for a CORS proxy server.

However, the most effective solution is to utilize the built-in Proxy to Backend functionality provided by angular-cli.

With this feature, you can define a specific route that redirects to your API, allowing you to make requests using relative URLs (such as /api) without encountering CORS restrictions.

Answer №3

Include the following code in your request options:

this._options = new RequestOptions({headers: headers, withCredentials: true});

You do not need to set all of those CORS headers as they are not effective. CORS headers should be configured in your response headers, not in the request.

On a side note, I have encountered an issue several times when reusing request options in Angular 2. It appears that you either need to set them at the http level or recreate the headers every time. Consider returning a new RequestOptions object each time instead of trying to reuse it, or utilize an HTTP interceptor or extend your HTTP service/request options to globally set the http RequestOptions.

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

casperjs timeout issue with an endless loop

Currently, I am utilizing casperjs to retrieve the content of a website that updates its values using websockets. Rather than attaching an event listener to each value, my goal is to scrape the entire website every 10 seconds. Here is the code snippet I a ...

Comparison of Ajax and submit: Why am I not receiving identical responses?

Utilizing Ajax for submission and all global variables ending in box. Note that the initialization code is functioning correctly. function begin() { if (confirm("Proceed at your own risk as all consequences are yours!!")) { var usernameNa ...

ng-for loop not properly rendering array of collections in table cells

I've been working on developing a MEAN Stack application that deals with mongoDB data related to hostels. hostels { "_id" : ObjectId("5e3c21c03d8d54b35af796ed"), "Hostel" : "The traveler's Lodge", "Rooms" : 23, "Customer" : [ { ...

Deploying CSS/JS files in Magento 2 is a crucial

Hello, I recently set up magento2 with the sample data included. After attempting to deploy static css/JS using the command php bin/magento setup:static-content:deploy, I didn't receive any errors but the issue persists. Additionally, I am unable to l ...

HTML- Any suggestions on how to troubleshoot my sticky navbar not functioning properly?

I'm having trouble creating a sticky navbar. I've attempted to use z-index: 999 but it's not behaving as expected. * { margin: 0; padding: 0; } .navbar { display: flex; align-items: center; justify-items: center; position: ...

Determining button click events in VueJS using the Watch method

Creating a feature for undo/redo in VueJS involves watching the settings and adding a new element to an array of changes when there is a setting change. Additionally, there is a method for undoing actions when the corresponding button is clicked. An issue ...

What are some methods to prevent cookies from being overridden?

Just beginning my journey in web development. Currently utilizing asp.net Web API and Angular with token authentication. Every time a user logs in, I set the token in a cookie and send it with each request. Everything has been running smoothly so far, bu ...

Storing HTML values in a Meteor database is a common practice for web

Within my meteor project, I have a paragraph in HTML containing a JSON value as follows: {"Active Template Id":"6467","Shirt Brand":"levis","ProductId":"EB301","Brand":"on","Material":"cotton","Price":"1800","Combo Id":"S90"} I am looking to store this v ...

Issues with my transpiled and typed TypeScript npm module: How can I effectively use it in a TypeScript project?

I'm trying to experiment with TypeScript. Recently, I created a simple "hello world" TypeScript module and shared it on npm. It's very basic, just has a default export: export default function hello(target: string = 'World'): void { ...

"Vue js: Embracing Labeling and Agile Transformation in Dynamic

Is it possible to dynamically change the input field's type and label between text, email, and number in Vue.js? I am new to this framework and would like to learn how to do this. <input type="email"> ...

A specialized solution designed to avoid loops in references

Is there a method to create a general solution that can prevent circular variables in JavaScript? This solution should be effective for any level of depth or type of circular reference, not limited to the variable itself... So far I've come up with t ...

Tips for effectively utilizing "Session" in jQuery

Are there any comparable features in jQuery to Session["Param"] in C#? How can I implement it? I've looked up "sessionStorage" in jQuery, but I'm having trouble grasping it. ...

Having trouble accessing the dashboard after uploading a document to Firestore

I am currently working on a project where I need to upload an audio file to Firebase storage and also add document data related to the audio file in Firestore database. The process involves recording the audio, uploading it to Firebase storage, submitting ...

Updating a document on Firestore based on a query is a straightforward process that involves first identifying

I'm currently working on a web form page that needs to update input fields into a specific firestore document based on certain conditions. Can anyone provide guidance on how this can be achieved? The initial part where I retrieve the query results se ...

"Enhance your website with a backspace button using jquery - here's

Recently, I delved into the world of jQuery and decided to test my skills by creating a jQuery calculator. Everything worked perfectly except for the backspace button. This is what I tried: if (value === backspace) { $(input).val($(input).val().substring ...

The clash between Traditional JavaScript and jQuery

As I pored over a textbook, I found myself stumped by an example problem. Here is the HTML code in question: $(function(){ $("#checkAll").click(function(){ $("[name=items]:checkbox").attr("checked", true); console.log("check all"); }); $("#checkNo").cl ...

Dealing with POST redirection and retrieving parameters in Next.js

In a typical scenario, browsers send GET requests and servers return pages. However, in my case, I am making requests to a remote server and need to receive responses. The issue is that the server redirects me back to my page via a POST request with some d ...

What is the best way to create a reset button for a timing device?

Is there a way to reset the timer when a button is clicked? Having a reset button would allow users to revisit the timer multiple times without it displaying the combined time from previous uses. Check out this code snippet for one of the timers along wit ...

How to Share Your Vuejs Component with the World by Publishing it on npm

I have recently developed a Vue.js 2 project using webpack which consists of 2 components. My goal is to share this project as an npm package so that the components can be easily reused in multiple projects. After publishing the project on npm with npm pu ...

Using Javascript closures for managing asynchronous Ajax requests within for loops

Let's consider the arrays provided below. var clients = ['a','b']; var reports = ['x','y','z']; var finalData = []; Now, I aim to iterate through them in a specific manner as shown. for(var i=0;i< ...