No 'Access-Control-Allow-Origin' header is present on the requested resource.

Livedoor의 날씨 웹 서비스 API는 JSON을 테스트하는 데 유용합니다. 문서에서 볼 수 있듯이 Livedoor 날씨 웹 서비스 API는 Ajax 통신을 쉽게 시도 할 때 유용합니다.

ぇ tp // 우아아테 r. 아오오오 r. 이 m/우아아테ぇr_는 cks/

평소에는 Node.js로부터의 액세스 밖에 시도하지 않습니다만, 최근 브라우저측(jQuery)으로부터 액세스 할 때가 있어 훌륭하게 CORS로 빠졌습니다. 제목대로. (CORS 회피인지 대책인지 말의 사용법 모호합니다만)

그래서 Access-Control-Allow-Origin를 피하는 서버를 세웠습니다.
어디까지나 API의 테스트 목적입니다.

엔드포인트



(잠시 기동하고 있다고 생각합니다만, 유지보수는 하지 않을 예정)

Azure Web Apps의 무료 플랜으로 설정

사용법



url 매개변수에 사용할 API 주소를 추가하여 GET 요청합니다.

  • h tp : // 코 rs- ぉ w. 어긋나는 b로 s. 네 t/? 우 rl = <사용 API 주소>

  • 예 : h tp : // 코 rs- ぉ w. 어긋나는 b로 s. 네 t/? Url = ht tp // 우우 아테 r. 아오오오 r. 코 m/후우레카 st/우ぇb세rゔぃ세/j 그런/v1? ty = 030010

    jQuery에서 사용해보기



    코피페로 움직인다고 생각합니다.

    글을 쓸 때 Chrome 58

    index.html
    <html>
        <head></head>
        <body>
            <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
            <script>
                'use strict';
    
                const AREA = `030010`; //盛岡市の天気
                let target = `http://weather.livedoor.com/forecast/webservice/json/v1?city=${AREA}`;
                target = `http://cors-allow.azurewebsites.net/?url=${target}`;
                $.ajax({
                    url: target,
                    data: 'json'
                })
                .done((res) => {
                    console.log(res);
                });
            </script>
        </body>
    </html>
    



    ※ 참고로 정상이라면 오류가 발생합니다.



    cros-allow.azurewebsite.net 측에는 향하고 있는 부분을 코멘트 아웃 해, 통상 액세스로 해 보면 에러입니다.

    index.html
    <html>
        <head></head>
        <body>
            <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
            <script>
                'use strict';
    
                const AREA = `030010`;
                let target = `http://weather.livedoor.com/forecast/webservice/json/v1?city=${AREA}`;
                // target = `http://cors-allow.azurewebsites.net/?url=${target}`;
                $.ajax({
                    url: target,
                    data: 'json'
                })
                .done((res) => {
                    console.log(res);
                });
            </script>
        </body>
    </html>
    
    No 'Access-Control-Allow-Origin' header is present on the requested resource.


    일단 내용



    익스프레스와 axios를 사용한 헹굼 서버입니다.
    Node.js v8.0

    server.js
    'use strict';
    
    const axios = require('axios');
    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    app.use(bodyParser());
    
    const PORT = process.env.PORT || 3000;
    
    // CORSを許可する
    app.use((req, res, next) => {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });
    
    app.get('/', (req, res) => {
      if(!req.query.url){
        const result = {
          error: 'You must parameter -> /?url=<API Address>'
        };
        res.send(result);
        return;
      }
    
      axios.get(req.query.url)
      .then((result) => {
        console.log(result);
        res.send(result.data);
      }).catch((err) => {
        console.error(err.response);
        console.error(err.response.data);
        const result = {
          error: {
            status: err.response.status,
            statusText: err.response.statusText
          }
        };
        res.send(result);
      });
    });
    
    app.listen(PORT);
    console.log(`Server running at ${PORT}`);
    

    그건 그렇고



    이 chrome 익스텐션을 사용하면 이런 일 없이 테스트할 수 있습니다. 참고로
    Allow-Control-Allow-Origin: * 라는 이름입니다. 그대로 웃음

    추가: WebApps 기능



    WebApps의 기능에 CORS의 제어가 있는 것 같기 때문에, 어플리케이션측에서 Access-Control-Allow-Origin: * 를 지정하지 않아도, 이쪽의 설정만으로도 갈 수 있을지도.

    좋은 웹페이지 즐겨찾기