行っていたこと
ローカル開発でフロントエンドとバックエンドを接続する際にエラーが起きた。
fetchでデータを引っ張る時にブラウザのコンソールでエラーを発見!
フロント側:http://localhost:8111(webpack)
バックエンド側:http://localhost:8080(express)
エラー内容
Access to fetch at ... from origin ...has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to
fetch the resource with CORS disabled.
CORSにブロックされた...
対応
yarn add cors
app.ts
import cors from "cors";
const app = express();
const corsOptions = {
origin: "http://localhost:8111",
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
最後に
バックエンド側でcorsを導入したら接続に成功しました!
※備忘録を兼ねて作成
参考記事