No access-control-allow-origin header is present on the requested resource. axios

I build an app use vue and codeigniter, but I have a problem when I try to get api, I got this error on console


Access to XMLHttpRequest at 'http://localhost:8888/project/login'
from origin 'http://localhost:8080' has been blocked by CORS policy:
Request header field access-control-allow-origin is not allowed
by Access-Control-Allow-Headers in preflight response.

I have been try like this on front-end (main.js)


axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

and this on backend (controller)


header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

and vue login method


this.axios.post('http://localhost:8888/project/login', this.data, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PATCH, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token"
}
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err.response);
});

I've searched and tried in stackoverflow but does not work, how I can solve it? thank you so much for your help


무명소졸의 웹개발

Code Fragment

Axios 를 통해 다른 서버를 통해 로그인 시도시 처리가 안되는 경우

§무명소졸§ 2020. 8. 26. 11:24

axios 를 쓰던 ES6 의 fetch 를 사용하던 다른 출처(Cross Origin)를 통해 로그인을 시도할 경우 정상적으로 JSESSIONID 값을 저장하지 못하는 경우가 있다. 오늘은 그 원인과 해결 방법을 알아보자 

Cross Origin 이란?

cross origin 이란 서로 다른 출처를 말하는 것 이다. 예를 들어 같은 호스트여도 port 가 다르면 출처가 다르다. 이 건 SOP 정책에 의한 것인데. 프로토콜, 도메인, Port 중 하나라도 다를 때 적용된다.

//not same origin http://localhost:3000 http://localhost:8080

Request.Crendentials

fetch API 를 이용할 경우 Request 라는 인터페이스를  이용한다. 해당 인터페이스에는 credentials 이라는 프로퍼티가 있는데 클라이언트 브라우저가 위에서 언급한 것 처럼 Cross Origin 요청일 경우 자격증명 설정에 대한 옵션을 가진다. Ajax 를 이용할 경우 withCredentials 옵션과 비슷하나 withCredentials 옵션이 true ,false 만 있는 거와는 달리 crendentials 옵션은 아래와 같은 세가지 옵션을 가진다.

omit cookie 금지
same-origin same Origin 일 경우 자격증명(Cookie ,Authorizaiton Header) 등을 허용 (default)
include cross-origin 호출이라도 자격증명(Cookie ,Authorizaiton Header)  등 정보를 허용 (단 CORS 헤더 값을 통한 SOP 회피를 해야된다)

same-origin 이 default 옵션이다. 그렇기 때문에 Cross-Origin 일 경우 자격 증명을 사용할 수 없는 것이다. 즉 사용하기 위해서는 include 로 설정해야 된다. AXIOS 를 사용할 경우 withCredentials : true  옵션을 주면  'include' 설정을 할 수 있다.

const handleLogin = () => { axios.post(`localhost:8080/login-action.do`, {}, {withCredentials: true} ).then(response => { }) }

CORS

요청에 대한 응답의 쿠키 정보를 활용하겠다고 설정만으로 끝나는게 아니다. 응답을 주는 서버 입장에서도 해당 응답 데이터의 접근을  CROSS-ORIGIN 에서 접근할 수 있도록 허용해 줘야 된다. 그러한 옵션이 CORS Header 인데 그중 아래 2가지 옵션을 설정해야 된다.

Access-Control-Allow-Origin: http://localhost:8080 Access-Control-Allow-Credentials: true

위 옵션에 대한 자세한 내용은 아래 링크를 참고하면 된다.

https://developer.mozilla.org/ko/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials

https://developer.mozilla.org/ko/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

똑같은 삽질은 2번 하지 말자

Javascript

Axios Access-Control-Allow-Origin issue

곽빵 2020. 4. 15. 11:06

Node.js (Server) + Vue.js (Front)

Axios

Promise (비동기 로직 자바스크립트 객체) 기반의 API 통신(HTTP) 라이브러리,

Vue에서 권고하는HTTP 통신 라이브러리는 액시오스(Axios)입니다. 

상대적으로 다른 HTTP 통신 라이브러리들에 비해 문서화가 잘되어 있고 API가 다양합니다.

npm - axios

axios

Promise based HTTP client for the browser and node.js

www.npmjs.com

No access-control-allow-origin header is present on the requested resource. axios

CORS

CORS란  Cross Origin Resource Sharing의 약자로, 

현재 Application의 도메인(웹페이지)에서 다른 웹페이지 도메인으로 리소스가 요청되는 경우를 얘기합니다.

예를 들면, 웹페이지인 http://web.com 에서 API서버 URL인 http://api.com 도메인으로 API를 요청하면

http 형태로 요청이 되므로 브라우저 자체에서 보안 상 이유로 CORS를 제한하게 되는 현상을 말합니다.

error: 405 Method Not Allowed

SPA(Single Page Application) 기반 앱을 RESTful API연동 방식으로 개발을 하다보면 API 서버와 웹페이지서버가 각각 따로 운영이 되므로 CORS 문제에 항상 부딪히는 경우가 다반사입니다.

해결방법

이 문제를 해결하기 위해서는 API 요청을 받는 쪽. 즉, API서버의 응답 헤더를 변경해주는 것으로 

해결 해 줄 수 있습니다. 서버 헤더 중 Access-Control-Allow-Origin이라는 헤더 프로퍼티가 있는데, 

이 헤더는 CORS를 허용해 주는 도메인을 설정해 주는 역할을 합니다.
이렇게 node.js Express기반의 API 서버에서 Access-Control-Allow-Origin 헤더를 

설정해줄 수 있는 cors npm 모듈이 있습니다. 

npm install --save corsconst express = require('express'); const cors = require('cors'); let corsOption = { origin: 'http://localhost:8000' // 허락하는 요청 주소 credentials: true // true하면 프론트에 쿠키를 공유할수있게된다. } app.use(cors(corsOption)); // CORS 미들웨어 추가

여러가지 설정도 추가 할 수 있기때문에 보안적인 이슈도 어느정도 예방할 수 있다.

이렇게 corsOption에 요청을 허락할 origin을 추가하는것으로  Access-Control-Allow-Origin이라는 값에 “http://localhost:8080”를 내려주고, 이후 응답을 받은 브라우저는 자신이 보냈던 요청의 Origin과 서버가 보내준

응답의 Access-Control-Allow-Origin을 비교해본 후 이 응답이 유효한 응답인지 아닌지를 판단한다.

그리고 유효한 응답의 경우에는 브라우저가 클라이언트 쪽으로 응답을 보내준다.

  ↓ 좀더 자세히 알고싶은 분들은 이하의 링크를 참조하시길! (상당히 이해하기 쉽게 잘 설명해 주셨습니다.)

https://evan-moon.github.io/2020/05/21/about-cors/

CORS는 왜 이렇게 우리를 힘들게 하는걸까?

이번 포스팅에서는 웹 개발자라면 한번쯤은 얻어맞아 봤을 법한 정책에 대한 이야기를 해보려고 한다. 사실 웹 개발을 하다보면 CORS 정책 위반으로 인해 에러가 발생하는 상황은 굉장히 흔해서

evan-moon.github.io

No access-control-allow-origin header is present on the requested resource. axios

How do I add Access

Solution.
Modify the header. In your get request, add the following to the header in the app.get function: res. header("Access-Control-Allow-Origin", "true"); ... .
Installing CORS. You can add the following code to your code to solve the issue: const cors = require('cors'); app. ... .
Using Express..

How do you set no CORS in Axios?

axios add no cors.
Axios({.
method: 'post',.
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },.
url: 'https://localhost:44346/Order/Order/GiveOrder',.
data: order..
}). then(function (response) {.
console. log(response. data);.

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.

Has been blocked by CORS policy no Access

[Solved] Axios request has been blocked by cors no 'Access-Control-Allow-Origin' header is present on the requested resource. Solution 1: Access-Control-Allow-Origin is a response header - so in order to enable CORS - We need to add this header to the response from server.