レベルエンター山本大のブログ

面白いプログラミング教育を若い人たちに

BLOCKVROCKリファレンス目次はこちら

astro+Restのサービスを作る時にCORSにならない方法

Astroからaxiosやfetchやらで、RestAPIを呼ぼうとするとCORSの制限に引っかかる。

ローカルだとClientとServerをそれぞれポートを分けて立てたりするから。

仮に以下のようにするとする

Astro => http://localhost:3000/

Server => http://localhost:8080/api/

Astro側のpackage.json"proxy": "http://localhost:8080/と、サーバーのホストを知らせてやれば良い。

{

 "name": "sampleservice",
 "type": "module",
 "proxy": "http://localhost:8080/,
 "version": "0.0.1",
 ・・・
}

サーバーサイドにも

import cors from "cors";

// 中略


// CORSをexpressに設定
const origin ="http://localhost:3000";
const app = express();
app.use(
  cors({
    origin: origin,
    credentials: true,
    preflightContinue: true,
  })
);

// 中略

const server = app.listen(config.get("server_port"), () => {
  console.log(config);
  console.log("listen to " + config.get("server_port"));
});