앞 뒤 상호작용 도 메 인 문제 해결 방안, 도 메 인 자원 공유 (CORS)

3213 단어
크로스 도 메 인 자원 공유 (CORS)
일반 크로스 도 메 인 요청: 서버 에서 Access - Control - Allow - Origin 만 설정 하면 됩 니 다. 전단 은 설정 할 필요 가 없습니다. 쿠키 요청 을 가 져 오 려 면 앞 뒤 가 모두 설정 되 어야 합 니 다.
주의해 야 할 것 은 같은 소스 정책 의 제한 으로 읽 은 쿠키 는 현재 페이지 가 아 닌 인터페이스 가 있 는 도 메 인 에 있 는 쿠키 를 요청 합 니 다.현재 페이지 쿠키 의 기록 을 실현 하려 면 다음 글 을 참고 하 십시오: 7. nginx 역방향 에이전트 에 proxy 를 설정 합 니 다.cookie_domain 과 8, NodeJs 미들웨어 에이전트 에서 cookieDomainRewrite 매개 변 수 를 설정 합 니 다.
현재 모든 브 라 우 저 는 이 기능 (IE8 +: IE8 / 9 는 XDomainRequest 대상 을 사용 하여 CORS 를 지원 해 야 함) 을 지원 하고 있 으 며, CORS 도 이미 주류 의 크로스 도 메 인 솔 루 션 이 되 었 다.
1. 전단 설정:
1.) 원생 ajax
//        cookie
xhr.withCredentials = true;

예제 코드:
var xhr = new XMLHttpRequest(); // IE8/9  window.XDomainRequest  

//        cookie
xhr.withCredentials = true;

xhr.open('post', 'http://www.domain2.com:8080/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
};

2.)jQuery ajax
$.ajax({
    ...
   xhrFields: {
       withCredentials: true    //        cookie
   },
   crossDomain: true,   //                ,    cookie
    ...
});

3. vue 프레임 워 크 는 vue - resource 에 포 장 된 ajax 구성 요소 에 다음 코드 를 추가 합 니 다.
Vue.http.options.credentials = true

2. 서버 설정:
백 엔 드 설정 이 성공 하면 전단 브 라 우 저 콘 솔 에 도 메 인 오류 메시지 가 나타 나 지 않 습 니 다. 반대로 설정 이 성공 하지 않 았 음 을 설명 합 니 다.
1.) 자바 배경:
/*
 *    :import javax.servlet.http.HttpServletResponse;
 *        :HttpServletResponse response
 */

//          :       (  +  +  ),          '/'
response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com"); 

//        cookie:     ,        '*',         ,        
response.setHeader("Access-Control-Allow-Credentials", "true"); 

2.) Nodejs 배경 예제:
var http = require('http');
var server = http.createServer();
var qs = require('querystring');

server.on('request', function(req, res) {
    var postData = '';

    //       
    req.addListener('data', function(chunk) {
        postData += chunk;
    });

    //       
    req.addListener('end', function() {
        postData = qs.parse(postData);

        //       
        res.writeHead(200, {
            'Access-Control-Allow-Credentials': 'true',     //       Cookie
            'Access-Control-Allow-Origin': 'http://www.domain1.com',    //       (  +  +  )
            /* 
             *      cookie  domain2   domain1,          cookie(nginx        ),
             *    domain2     cookie  ,          domain2   cookie,               
             */
            'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly'  // HttpOnly     js    cookie
        });

        res.write(JSON.stringify(postData));
        res.end();
    });
});

server.listen('8080');
console.log('Server is running at port 8080...');

좋은 웹페이지 즐겨찾기