CORS ์๋ฌ ํด๊ฒฐํ๊ธฐ + Reverse Proxy server ๊ตฌ์ถ with Nginx
์์ ๊ฐ์ด React์์ ์ธ๋ถ api๋ก ์์ฒญ์ ๋ณด๋ด๋ ๊ฒฝ์ฐ, CORS ์๋ฌ๊ฐ ๋ฌ๋ค.CORS๋ Cross Origin Resource Sharing๋ก, ์๋ก ๋ค๋ฅธ ์ถ์ฒ ๊ฐ์ ์์์ ๊ณต์ ํ๋ ๊ฒ์ ๋งํ๋ค. ๊ธฐ๋ณธ์ ์ผ๋ก ๋ธ๋ผ์ฐ์ ธ๋ ๋์ผ
velog.io
์ ๋ธ๋ก๊ทธ๋ฅผ ์ฐธ๊ณ ํ์ต๋๋ค!! โบ๏ธโบ๏ธ
https://avoc-o-d.tistory.com/90
[React/JS] Image URL์ ํ์ผ ๊ฐ์ฒด(File object)๋ก ๋ณ๊ฒฝํ๊ธฐ
const convertUrlToFile = async (url) => { const response = await fetch(url); const data = await response.blob(); const filename = url.split("/").pop(); // url์์ ํ์ผ๋ช ์ถ์ถ const ext = url.split(".").pop(); // url์์ ์ด๋ฏธ์ง ํ์ ์ถ์ถ con
avoc-o-d.tistory.com
์ฐ์ ์ ๋ Iimage URL๋ก api์์ฒญํ ๋, CORS ์๋ฌ๋ฅผ ์ง๋ฉดํ์ต๋๋ค...
ํด๊ฒฐํด๋ด ์๋ค!!!!๐๐๐
์๋๋ ๊ฒฐ๋ก ์ ์ผ๋ก ํด๊ฒฐํ ์ฝ๋์ ๋๋ค..
import axios from 'axios'
const media = axios.create({
baseURL: "/media/",
});
// url -> file ๊ฐ์ฒด
async function convertURLtoFile(url) {
let result;
const filename = url.split("/").pop(); // url์์ file ์ด๋ฆ ์ถ์ถ
await media.get(url, { responseType: "blob" }).then((res) => {
// File ํ์์ ๋ง๊ฒ ํ์ผ ์์ฑ
result = new File([res.data], filename, {
type: res.data.type,
});
});
return result;
}
00. http-proxy-middleware ํจํค์ง ๋ค์ด๋ก๋
npm install http-proxy-middleware
01. setupProxy.js ํ์ผ ์์ฑ
src/setupProxy.js
๋ฐ๋์ src ํด๋์ ๋ฐ๋ก ์๋์ setupProxy.js์ ์์ฑํ์ฌ์ผ ํ๋ก์ ์ค์ ์ ์ธ์ํ ์ ์์ต๋๋ค. ๐
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
"/media",
createProxyMiddleware({
target: ์์ฒญํ API ์ฃผ์,
changeOrigin: true,
})
);
};
์ ๋ ์ด๋ฏธ์ง ์์ฒญ์ ์ํด โจ /media โจ ์ดํ url๋ก ์์ฒญ์ ๋ณด๋ด๋๋ก ํ๋ก์ ์ค์ ์ ํด์คฌ์ต๋๋ค.
02. ์ธ์คํด์ค ์์ฑ - create
์ธ์คํด์ค๋ฅผ ํ๋ ์์ฑํด์ axios ์ธํ ์ ํด์ค๋๋ค!
import axios from 'axios'
const media = axios.create({
baseURL: "/media/",
});
// image url๋ก API ์์ฒญ
media.get(url).then((res) => {
// res ์์ฒญ ๊ฒฐ๊ณผ~~
});
03. ์ด๋ฏธ์ง url๋ก API ์์ฒญ
import axios from 'axios'
const media = axios.create({
baseURL: "/media/",
});
// url -> file ๊ฐ์ฒด
async function convertURLtoFile(url) {
let result;
const filename = url.split("/").pop(); // url์์ file ์ด๋ฆ ์ถ์ถ
await media.get(url, { responseType: "blob" }).then((res) => {
// File ํ์์ ๋ง๊ฒ ํ์ผ ์์ฑ
result = new File([res.data], filename, {
type: res.data.type,
});
});
return result;
}
์ฃผ์ ๊น๊ฒ ์ดํด๋ณผ ๋ถ๋ถ!
๐ฅ { responseType: "blob" } ๋ฅผ ํตํด Blob ํํ๋ก ๊ฐ์ ธ์ต๋๋ค.
๐ฅ { type: res.data.type } ๋ฅผ ํตํด File์ type์ Blob์ type ๊ทธ๋๋ก ์ง์ ํด์ค๋๋ค.
{ responseType: "blob" }์ ์ ํด์ฃผ๋ฉด ์ด๋ ๊ฒ ๋ฐ์ด๋๋ฆฌ string์ด ์์!
๐๐๐์(์ํ)๊ณ (ํต๋ฐ๋)..CORS...๐ญ๐ญ๐ญ