カテゴリー
開発中のSvelte/SvelteKitのDevサーバーのCORS対策
※ 当ページには【広告/PR】を含む場合があります。
2024/12/18

http://localhost

Viteのサーバープロキシ機能

vite.config.ts(もしくはvite.config.js)
import { defineConfig } from 'vite';
// ...
export default defineConfig({
// ...
server: {
proxy: {
'/api': {
target: "https://hoge.piyo.com",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})
http://localhost:12345/api
target
https://hoge.piyo.com/api
/api
rewrite
rewrite
https://hoge.piyo.com/api
/api
https://hoge.piyo.com
cosnst url = 'https://hoge.piyo.com/?huga=moga&buyo=jifo';
const urlForProxy = url.replace(/^https\:\/\/hoge\.piyo\.com/m, '/api');
const response = await fetch(urlForProxy, {
method: 'GET',
headers: {
'content-type': 'application/json'
},
});
const rslt = await response.text();
//OR, const rslt = await response.json();
console.log(rslt);

余談〜ViteのCORS設定の注意点
cors: true
import { defineConfig } from 'vite';
// ...
export default defineConfig({
// ...
server: {
cors: true
}
})

Express/CORS
まとめ
記事を書いた人
ナンデモ系エンジニア
主にAngularでフロントエンド開発することが多いです。 開発環境はLinuxメインで進めているので、シェルコマンドも多用しております。 コツコツとプログラミングするのが好きな人間です。
カテゴリー