0
0

CORSって何?

Posted at

CORS(Cross-Origin-Resource-Sharing)とは、異なるオリジンとのデータ交換を可能にするもの。

オリジンって?

  • URLのホスト
  • プロトコル
  • ポート番号

上記3つで構成されている識別子のこと

上記3つがすべて同一の場合、同一オリジン。

基本的に、同一オリジンでしかデータ交換はできない。

異なるオリジン間のデータ交換

クライアント側はreact、サーバ側はexpressで作成してみる。

import { useEffect, useState } from "react";
import axios from "axios";

function App() {
  const [message, setMessage] = useState("");

  useEffect(() => {
    axios.get("http://localhost:3000/api/message").then((res) => {
      setMessage(res.data);
    });
  }, []);

  return (
    <>
      <h1>hello</h1>
      <p>{message}</p>
    </>
  );
}

export default App;

const express = require("express");
const app = express();

const server = app.listen(3000, () => {
  console.log("server start");
});

app.get("/api/message", (req, res, next) => {
  res.json("hello");
});

異なるポートで動作させているので、

Access to XMLHttpRequest at 'http://localhost:3000/api/message' from origin 'http://localhost:5000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

上記のようなエラーが出る。

Access-Conrtol-Allow-Origin

異なるオリジンとデータ交換を許可するための仕掛け。

上記のコードでデータのやり取りをするためには

react側のpackage.jsonに

"proxy": "http://localhost:3000/",

を追加する

express側では

const cors = require("cors");

app.use(
  cors({
    origin: "http://localhost:5173",
    credentials: true,
    optionsSuccessStatus: 200,
  })
);

を追加する。

そうすることで、異なるオリジン間でもデータのやり取りができるようになる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0