No access-control-allow-origin header is present on the requested resource in angular

최종 업데이트 날짜: 2022년 6월 16일

Amazon CloudFront에서 요청한 리소스에 CORS 오류 "No 'Access-Control-Allow-Origin'"이 발생합니다. 이 문제가 발생하는 이유는 무엇이며 어떻게 해결할 수 있나요?

해결 방법

참고: AWS Command Line Interface(AWS CLI) 명령을 실행할 때 오류가 발생할 경우 AWS CLI의 최신 버전을 사용하고 있는지 확인하세요.

다음 명령을 실행하여 오리진 서버가 Access-Control-Allow-Origin 헤더를 반환하는지 확인합니다. example.com을 필수 오리진 헤더로 바꿉니다. https://www.example.net/video/call/System.generateId.dwr을 헤더 오류를 반환하는 리소스의 URL로 바꿉니다.

curl -H "Origin: example.com" -v "https://www.example.net/video/call/System.generateId.dwr"

CORS 정책이 오리진 서버가 Access-Control-Allow-Origin 헤더를 반환하도록 허용하는 경우 다음과 유사한 응답이 표시됩니다.

HTTP/1.1 200 OK Server: nginx/1.10.2 Date: Mon, 01 May 2018 03:06:41 GMT Content-Type: text/html Content-Length: 3770 Last-Modified: Thu, 16 Mar 2017 01:50:52 GMT Connection: keep-alive ETag: "58c9ef7c-eba" Access-Control-Allow-Origin: example.com Accept-Ranges: bytes

오리진 서버에서 CORS 정책을 설정한 후 오리진 헤더를 오리진 서버로 전달하도록 CloudFront 배포를 구성합니다. 오리진 서버가 Amazon S3 버킷인 경우 다음 헤더를 Amazon S3에 전달하도록 배포를 구성합니다.

  • Access-Control-Request-Headers
  • Access-Control-Request-Method
  • 오리진

오리진 서버에 헤더를 전달하기 위해 CloudFront에는 오리진 유형에 따라 CORS-S3OriginCORS-CustomOrigin이라는 두 가지 사전 정의된 정책이 있습니다.

배포에 사전 정의된 정책을 추가하려면 다음을 수행합니다.

  1. CloudFront 콘솔에서 배포를 엽니다.
  2. 동작(Behaviors) 탭을 선택합니다.
  3. 동작 생성을 선택합니다. 또는 기존 동작을 선택한 다음 편집을 선택합니다.
  4. 캐시 키 및 오리진 요청에서 캐시 정책 및 오리진 요청 정책을 선택합니다. 그런 다음 오리진 요청 정책에 대해 드롭다운 목록에서 CORS-S3Origin 또는 CORS-CustomOrigin을 선택합니다. 자세한 내용은 관리형 오리진 요청 정책 사용을 참조하세요.
    참고: 대신 자체 캐시 정책을 생성하려면 캐시 정책 생성을 참조하세요.
  5. 동작 생성을 선택합니다. 또는 기존 동작을 편집하는 경우 변경 사항 저장을 선택합니다.

캐시 정책을 사용하여 헤더를 전달하려면 다음을 수행합니다.

  1. 캐시 정책을 생성합니다.
  2. 캐시 키 설정에서 헤더에 대해 다음 헤더 포함을 선택합니다. 헤더 추가 드롭다운 목록에서 오리진에 필요한 헤더 중 하나를 선택합니다.
  3. 정책을 연결할 동작에 필요한 대로 캐시 정책 설정을 채웁니다.
  4. 캐시 정책을 CloudFront 배포의 동작에 연결합니다.

레거시 캐시 설정을 사용하여 헤더를 전달하려면 다음을 수행합니다.

  1. CloudFront 콘솔에서 배포를 엽니다.
  2. 동작(Behaviors) 탭을 선택합니다.
  3. 동작 생성을 선택합니다. 또는 기존 동작을 선택한 다음 편집을 선택합니다.
  4. 캐시 키 및 오리진 요청에서 레거시 캐시 설정을 선택합니다.
  5. 헤더 드롭다운 목록에서 오리진에 필요한 헤더를 선택합니다. 사용자 정의 추가를 선택하여 오리진에 필요한 헤더 중 드롭다운 목록에 없는 헤더를 추가합니다.
  6. 동작 생성을 선택합니다. 또는 기존 동작을 편집하는 경우 변경 사항 저장을 선택합니다.

참고: 또한 클라이언트 요청의 일부로 헤더를 CloudFront에 전달해야 합니다. 그러면 CloudFront가 오리진에 헤더를 전달합니다.

CloudFront 배포의 캐시 동작이 HTTP 요청에 대한 OPTIONS 메서드를 허용하도록 구성

CORS 정책을 업데이트하고 적절한 헤더를 전달한 후에도 오류가 발생하면 배포의 캐시 동작에서 OPTIONS HTTP 메서드를 허용합니다. 기본적으로 CloudFront는 GET 및 HEAD 메서드만 허용합니다. 그러나 일부 웹 브라우저에서는 OPTIONS 메서드에 대한 요청을 발행할 수 있습니다. CloudFront 배포에서 OPTIONS 메서드를 활성화하려면 다음을 수행합니다.

  1. CloudFront 콘솔에서 배포를 엽니다.
  2. 동작(Behaviors) 탭을 선택합니다.
  3. 동작 생성을 선택합니다. 또는 기존 동작을 선택한 다음 편집을 선택합니다.
  4. 허용되는 HTTP 메서드에서 GET, HEAD, OPTIONS를 선택합니다.
  5. 동작 생성을 선택합니다. 또는 기존 동작을 편집하는 경우 변경 사항 저장을 선택합니다.

오리진 서버에 액세스할 수 없거나 적절한 CORS 헤더를 반환하도록 설정할 수 없는 경우 필요한 CORS 헤더를 반환하도록 CloudFront를 구성합니다. 구성하려면 응답 헤더 정책을 생성합니다.

  1. CloudFront 콘솔에서 배포를 엽니다.
  2. 동작(Behaviors) 탭을 선택합니다.
  3. 동작 생성을 선택합니다. 또는 기존 동작을 선택한 다음 편집을 선택합니다.
  4. 응답 헤더 정책의 경우
    드롭다운 목록에서 기존 응답 정책을 선택합니다.
    -또는-
    정책 생성을 선택하여 새 응답 헤더 정책을 생성합니다. 새 정책의 교차 오리진 리소스 공유에서 CORS를 활성화합니다.
  5. 필요에 따라 다른 설정을 입력하고 정책 생성을 선택합니다.
  6. 동작 생성 페이지의 드롭다운 목록에서 생성한 정책을 선택합니다.
  7. 동작 생성을 선택합니다. 또는 기존 동작을 편집하는 경우 변경 사항 저장을 선택합니다.

참고: CloudFront는 일반적으로 5분 이내에 배포에 변경 사항을 배포합니다. 배포를 수정한 후에는 캐시를 무효화하여 이전에 캐시된 응답을 지웁니다.


이 문서가 도움이 되었나요?


결제 또는 기술 지원이 필요합니까?

Internet Explorer에 대한 AWS 지원이 07/31/2022에 종료됩니다. 지원되는 브라우저는 Chrome, Firefox, Edge 및 Safari입니다. 자세히 알아보기 »

In this article, we'll go through how to use the Angular CLI proxy setup to address CORS errors in our front-end Angular 13 project.

CORS, which stands for Cross-Origin Resource Sharing, enables a server to regulate which front-end JavaScript clients may access server resources. It works by delivering HTTP headers with HTTP responses that instruct web browsers whether to allow or deny frontend JavaScript code from accessing responses.

CORS headers are basic HTTP headers that instruct a browser to enable a web application operating at one origin (domain) to access particular resources from another origin's server.

Browser security disallow you from making cross-domain requests except if the HTTP response has a Control-Allow-Origin header with a * value or the domain of your client.

CORS issues are framework-agnostic and may occur in any front-end JavaScript application built with plain JS, React or Vue.js, etc. but in our case, we'll see how to solve CORS issues in the context of an Angular 13 application.

What causes CORS errors in Angular development

A front-end developer's primary responsibility is to access back-end APIs. It is also probable that your front-end application may need to communicate with a server from a different location on a regular basis. For example, you might use your own server, or you could use a third-party API that your application needs.

You may encounter a cross-origin resource sharing (CORS) issue in any of these situations. What exactly is CORS? What are the best practices for interacting with your back-end services? How to utilize CORS in an Angular application will be explained in this post.

Because of security concerns, web browsers impose a "same origin" policy on all web applications. Browser clients are only permitted to interact with servers that share their origin. In the case of Angular, we often need to create a full-stack application with separated client and server apps. As a result, if your front end tried to access a resource from your server that is located in a location with different origins, the browser would throw an error.

Your browser must be informed that your client and server may share resources even if they are located in different places by configuring cross-origin resource sharing (CORS).

On development; since Angular CLI offers a development server that runs on localhost:4200 by default, if you use a back-end server that runs on a different domain, you may have CORS issues if your server is not correctly setup.

Even though your backend runs on localhost, it will listen on a different port, which is considered as a separate domain.

How to resolve CORS issues with Angular 13

We now understand why CORS problems may arise while implementing your Angular application. How can they be fixed?

There are two options:

  • Configure the server to transmit the necessary CORS headers
  • Set up the Angular CLI proxy

The apparent approach is to correctly setup the backend server, however this is not always achievable. You may not have access to the server code, for example.

Also check out an example of how to configure CORS with TypeScript and Node/Nest.js backend

Most server languages and frameworks provide easy APIs to configure CORS. For example, in PHP, you can simply add the following lines to your PHP file:

header('Access-Control-Allow-Origin: *');

In Node.js and Express server, you can use the cors package (npm i cors --save) as follows:

const cors = require('cors'); const express = require('express'); const app = express();app.use(cors());

In this angular tutorial, we will learn step by step how to use Angular CLI proxy to fix CORS issues.

Prepare your Angular 13 project

At this step, we expect that you alreay have an Angular project with some code to send HTTP requests and CORS. Otherwise, you need to create a project and some code for sending requests to a server.

Open a new command-line interface and navigate to the root folder of your project.

Create a proxy configuration file for Angular 13 CLI

Next, create src/proxy.conf.json file and add the following content:

{ "/api/*": { "target": "http://localhost:3000", "secure": false, "logLevel": "debug" } }

This configuration file specifies that any HTTP request which starts with the /app/ path will be sent to the proxy which will redirect it to the target hostname.

The secure option is used to enforce usage of SSL.

See all the available options from webpack dev server documentation.

Add a proxyConfig key to angular.json

Next, open the angular.json file and add a proxyConfig key under the serve->options that points to the src/proxy.conf.json file as follows:

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

Serving your Angular 13 application

Finally, use the following command to start the dev server with this proxy configuration:

If you do any changes in the proxy configuration file afterwards, make sure to re-run the ng serve command.

You can find more information about the proxy configuration in the Angular CLI from the docs

Conclusion

As a re-wrap, when developing with Angular 13, developers may encouter CORS errors.

Accessing back-end APIs is one of the most important tasks of a front-end developer. Furthermore, your front-end application will frequently need to connect with a server of a different origin. This might be your own server or a third-party application programming interface that your application requires.

In any of these scenarios, it's possible that you'll run into CORS problems if you use Angular CLI with a back-end server running on a different domain than the one provided by the CLI by default (localhost:4200).

A separate port is used to represent a different domain even if your backend server is operating on your local machine's IP address.

In this post, we'll went over how to leverage the Angular CLI proxy configuration to solve CORS problems in our front-end Angular 13 project.

Servers may control which JavaScript clients can access server resources using CORS (Cross-Origin Resource Sharing). Front-end JavaScript code may access responses only if it is allowed or denied by HTTP headers that are sent with the response to an HTTP request.

HTTP headers designed for CORS instruct a browser to allow a web application from one origin (domain) to access resources from another origin's server.


  • Author: Ahmed Bouchefra Follow @ahmedbouchefra
  • Date: 23 Apr 2022

How do you fix no Access

How do I fix the No access-control error on Windows 10?.
Make changes at the server level. If you have access to the server, enable CROS requests by adding Access-Control-Allow-Origin: * header. ... .
Run your own proxy server. ... .
Disable the Same Origin Policy in your browser..

How do I fix CORS header Access

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.

How do I add Access

For IIS6.
Open Internet Information Service (IIS) Manager..
Right click the site you want to enable CORS for and go to Properties..
Change to the HTTP Headers tab..
In the Custom HTTP headers section, click Add..
Enter Access-Control-Allow-Origin as the header name..
Enter * as the header value..
Click Ok twice..

How do you solve CORS issue in angular 8?

CORS error due to browser's same origin policy. To get around this, you need to tell your browser to enable your client and your server to share resources while being of different origins. In other words, you need to enable cross-origin resource sharing or CORS in your application.