[ajax] CORS : 신임 정보 플래그가 true 인 경우 Access-Control-Allow-Origin에서 와일드 카드를 사용할 수 없습니다.

관련 설정이 있습니다

프론트 엔드 서버 (Node.js, 도메인 : localhost : 3000) <—> 백엔드 (Django, Ajax, 도메인 : localhost : 8000)

브라우저 <-webapp <-Node.js (앱 제공)

브라우저 (webapp)-> Ajax-> Django (Serve ajax POST requests)

이제 내 문제는 webapp가 백엔드 서버에 Ajax 호출을하는 데 사용하는 CORS 설정입니다. 크롬에서는 계속

신임 정보 플래그가 true 인 경우 Access-Control-Allow-Origin에서 와일드 카드를 사용할 수 없습니다.

파이어 폭스에서도 작동하지 않습니다.

내 Node.js 설정은 다음과 같습니다

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:8000/');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
};

그리고 장고에서는 이 미들웨어이것 과 함께 사용하고 있습니다

webapp는 다음과 같이 요청합니다.

$.ajax({
    type: "POST",
    url: 'http://localhost:8000/blah',
    data: {},
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    dataType: 'json',
    success: successHandler
});

따라서 webapp가 보내는 요청 헤더는 다음과 같습니다.

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept"
Access-Control-Allow-Methods: 'GET,PUT,POST,DELETE'
Content-Type: application/json 
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: csrftoken=***; sessionid="***"

응답 헤더는 다음과 같습니다.

Access-Control-Allow-Headers: Content-Type,*
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: application/json

내가 잘못 가고있는 곳?!

편집 1 :을 사용 chrome --disable-web-security하고 있지만 실제로는 실제로 작동하기를 원합니다.

편집 2 : 답변 :

그래서 나를위한 솔루션 django-cors-headers구성 :

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000' # Here was the problem indeed and it has to be http://localhost:3000, not http://localhost:3000/
)



답변

이것은 보안의 일부이므로 그렇게 할 수 없습니다. 자격 증명을 허용 Access-Control-Allow-Origin하려면 사용하지 않아야합니다 *. 정확한 프로토콜 + 도메인 + 포트를 지정해야합니다. 참고로 다음 질문을 참조하십시오.

  1. Access-Control-Allow-Origin 와일드 카드 하위 도메인, 포트 및 프로토콜
  2. 자격 증명을 사용하여 원본 간 리소스 공유

게다가 *너무 관대하며 자격 증명 사용을 물리 칠 것입니다. 따라서 http://localhost:3000또는 http://localhost:8000출발지 허용 헤더로 설정 하십시오.


답변

CORS 미들웨어를 사용 중이고 withCredential부울 true 를 보내려는 경우 다음 과 같이 CORS를 구성 할 수 있습니다.

var cors = require('cors');
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));


답변

사용중인 경우 미들웨어를 작성하는 대신 cors 패키지를 사용하여 CORS를 허용 express할 수 있습니다 .

var express = require('express')
, cors = require('cors')
, app = express();

app.use(cors());

app.get(function(req,res){
  res.send('hello');
});


답변

시도 해봐:

const cors = require('cors')

const corsOptions = {
    origin: 'http://localhost:4200',
    credentials: true,

}
app.use(cors(corsOptions));


답변

모든 출처를 허용하고 자격 증명을 true로 유지하려면 다음과 같이하십시오.

app.use(cors({
  origin: function(origin, callback){
    return callback(null, true);
  },
  optionsSuccessStatus: 200,
  credentials: true
}));


답변

(편집) 이전에 권장 된 추가 기능을 더 이상 사용할 수 없습니다. 다른 방법으로 시도해 볼 수 있습니다


Chrome에서 개발 목적 으로이 애드온을 설치
하면 특정 오류가 제거됩니다.

Access to XMLHttpRequest at 'http://192.168.1.42:8080/sockjs-node/info?t=1546163388687'
from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the
'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'
when the request's credentials mode is 'include'. The credentials mode of requests
initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

설치 후 Intercepted URLsAddOn의 ( CORS , green 또는 red) 아이콘을 클릭하고 적절한 텍스트 상자를 채워서 URL 패턴을 추가하십시오 . 예제 URL 패턴에 맞는지 여기에 추가 http://localhost:8080될 것이다 :*://*


답변

이것은 개발에서 나에게 도움이되지만 프로덕션에서는 아직 언급되지 않았지만 아마도 최선의 방법은 아닌 다른 일을 수행 할 수 있다고 조언 할 수는 없습니다. 어쨌든 여기에 간다 :

요청에서 오리진을 가져온 다음 응답 헤더에서 오리진을 사용할 수 있습니다. 표현 방식은 다음과 같습니다.

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.header('origin') );
  next();
});

파이썬 설정에서 어떤 모습 일지 모르겠지만 번역하기 쉽습니다.