CORS(Cross-Origin Resource Sharing) 처리방안

 

1. 처리방안

1안) 서버 측에서 Access-Control-Allow-Origin 헤더를 설정하여 클라이언트의 요청 출처를 허용하는 것.

2안) 프록시 서버를 사용하거나, 브라우저 확장 프로그램을 활용하는 방법.

 

openapi 호출할 때 CORS가 발생하여, 1안으로는 해결할 수 없어서 2안으로 진행함.

 

2. 구현절차

2.1 proxy module 설치

npm install http-proxy-middleware

 

2.2 proxy module 설정

setupProxy.js 파일을 생성하고, 설정한다.

 

 - 호출 하려는 url: https://apihub.kma.go.kr/api/typ02/openApi/VilageFcstMsgService/getLandFcst?pageNo=1&numOfRows=10&dataType=JSON&regId=11B20601&authKey=인증키

 

 - proxy로 호출하는 url: http://localhost:3001/proxy/api/typ02/openApi/VilageFcstMsgService/getLandFcst?pageNo=1&numOfRows=10&dataType=JSON&regId=11B20601&authKey=인증키

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/proxy',
    createProxyMiddleware({
      target: 'https://apihub.kma.go.kr',
      changeOrigin: true,
      })
    );
};

 

매핑된 /proxy는 client에서 proxy 구분으로 사용될 뿐, 실제서버에서는 url에 들어가지 않음. (react 버전 19.2.0 기준)

 

2.3. proxy url로 호출

import React, { useState } from 'react';
import './App.css';

function App() {
  // const [temp, setTemp] = useState("");
  const [isReady, setIsReady] = useState(false);
  const [data, setData] = useState(null);
 

  const params = new URLSearchParams({
    pageNo: 1,
    numOfRows: 10,
    dataType: 'JSON',
    regId: '11B20601', // 수원지역
    authKey: '인증키'
  });

  React.useEffect(() => {
    fetch(`proxy/api/typ02/openApi/VilageFcstMsgService/getLandFcst?${params.toString()}`)
      .then(response => response.json())
      .then(data => {
        setData(data.response.body.items.item);
        setIsReady(true);
      })
      .catch(error => console.error('Error fetching data:', error));
  }, []);

  if(isReady) {
    return (
      <div className="App">
        <h1>Weather Data</h1>
        <table border="1">
          <thead>  
            <tr>
              <th>Announce Time</th>
              <th>지역코드</th>
              <th>발효번호(발표시간기준)</th>
              <th>날씨</th>
              <th>강수확률</th>
              <th>풍향1</th>
              <th>풍향2</th>
            </tr>
          </thead>
          <tbody>
            {data && data.map((item, index) => (
              <tr key={index}>
                <td>{item.announceTime}</td>
                <td>{item.regId}</td>
                <td>{item.numEf}</td>
                <td>{item.wf}</td>
                <td>{item.rnSt}</td>
                <td>{item.wd1}</td>
                <td>{item.wd2}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  } else {
    return (
      <div className="App">
        Loading...
      </div>
    );
  }

}

export default App;

 

 

결과

 

end.

 

'Programming Language > React' 카테고리의 다른 글

package.json 버전 표기법  (0) 2021.04.27

 

https://www.irfanview.com/

 

IrfanView - Official Homepage - One of the Most Popular Viewers Worldwide

I would like to sincerely thank all you faithful IrfanView users who send me messages of good wishes, congratulations and appreciation. THANKS ! Irfan Skiljan. About the Author

www.irfanview.com

 

최신 이미지 자동으로 보는 방법

- 기능중에, "Options > Hotfolder (watch folder)..." 를 설정하면, 해당 폴더의 최신 이미지가 업데이트되면 자동으로 표시된다.

 

 

https://supawer0728.github.io/2018/03/22/spring-multi-transaction/

 

(Spring)다중 DataSource 처리

서론Spring Application을 만들면서 여러 DataSource와 transaction이 존재하고 하나의 transaction 내에 commit과 rollback이 잘 동작하도록 하려면 어떻게 설정해야 할까? 실제로 구현을 해본 적은 없지만 세 가지

supawer0728.github.io

 

 

https://goodwoong.tistory.com/126

 

[Spring boot] 분산 트랜젝션

분산 트랜젝션이란 ? 2개 그 이상의 네트워크 상의 시스템 간의 트랜잭션. 2개의 Phase Commit으로 분산 리소스간의 All or Nothing 보장 Spring Boot 내에서 XA protocol을 사용해서 two phase commit을 진행한다. XA

goodwoong.tistory.com

 

 

https://kindloveit.tistory.com/120

 

[Spring boot] atomikos 라이브러리 활용 XA 멀티 DBMS Transacaction 구현

백엔드 개발을 할때 하나의 DB 가 아닌 여러 DB를 활용해서 개발을 해야 할 경우가 있을 수 있다. 여러 DB에 데이터를 write 할 경우에 데이터 정합성을 위한 transaction 관리가 쉽지 않을텐데 Spring boot

kindloveit.tistory.com

 

참조.

- atomikos : https://www.atomikos.com/Documentation

 

 

 

'Tools > Spring' 카테고리의 다른 글

Spring 관련 한글 문서  (0) 2023.10.06
[SpringBoot 2.7.*] H2 Jdbc 설정, schema(DDL) 및 data(DML)  (0) 2023.09.16
spring application.properties 정보  (0) 2023.08.18
J2DBC 참조  (0) 2023.05.09
web Flux 참조  (0) 2023.05.09

 

jsp 를 이용한 로직, 또는 windows 의 tasklist 나, unix/linux의 ps 를 이용할 수도 있다.

	private static boolean checkRunningJarProcesses(String checkProcess) {
        boolean jarProcessFound = false;
        if(checkProcess == null) {
        	return jarProcessFound;
        }        	
        
        checkProcess = checkProcess.trim();
        
    	// 환경설정. 1) JAVA_HOME 정의하고, 2) path에 %JAVA_HOME%\bin 추가할 것.  
    	String command = "jps";
        String line;
        Process process = null;
        try {
            process = new ProcessBuilder(command).start();
            logger.debug("Checking for running JAR processes...");
            try(BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                while ((line = reader.readLine()) != null) {
                    // "java -jar"가 포함된 프로세스를 찾음
                	String[] columns = line.split(" "); // 1: pid, 2: process
                    if (columns.length > 1 && checkProcess.equalsIgnoreCase(columns[1])) {
                    	logger.debug("Found JAR process: " + line);
                        jarProcessFound = true;
                    }
                }            
            }        	
            // int returnCode = process.waitFor();
            // logger.debug("returnCode: {}", returnCode);
        } catch (IOException e) {
        	logger.error(e.toString());
	    } finally {
	    	if(process != null) {
	            process.destroy();
	    	}
	    }
		
		return jarProcessFound;
	}

 

end.

+ Recent posts