2
2

More than 1 year has passed since last update.

ローカル環境下でSpringBootのRestApiをNextjsから叩く 結論:Contollerクラスに@CrossOrigin付与して解決

Last updated at Posted at 2022-12-18

概要

SpringBootのRestApiをNext.jsから使います。

Apiはクライアントサイドで叩く方法を採用します。

SpringBootのURL:http://localhost:5000
Next.jsのURL:http://127.0.0.1:3000/

開発環境

OS:windows10

バックエンド側:
IDE:IntelliJ Community
spring-boot-starter-parent 2.75
java : 11

Postman:Windows版 検証用

フロントエンド:
IDE:VScode
Next.js
├── @types/node@18.11.15
├── @types/react-dom@18.0.9
├── @types/react@18.0.26
├── eslint-config-next@13.0.6
├── eslint@8.29.0
├── next@13.0.6
├── react-dom@18.2.0
├── react@18.2.0
├── styled-components@5.3.6
├── styled-jsx@5.1.1
└── typescript@4.9.4

手順

SpringBoot側の設定 @CrossOriginアノテーション付与

Next.jsからのCORを許可するために@CrossOriginアノテーションを追加します。

Contoller.java
@Data
class Sampledata{
    String name;
    float price;

    public Sampledata(String name, float price) {
        this.name = name;
        this.price = price;
    }
}

@RestController
@CrossOrigin(origins = "http://127.0.0.1:3000")
public class ProductRestController {


    @GetMapping("/api/products")
    public Sampledata hello(){
        return new Sampledata("うまい棒",12);
    }
}

実行してPostmanで動きを確認します。OKです。
ただし@CrossOriginが効いてるかは確認できてません。
あくまでバックエンドの確認ですね。

image.png

Next.js側の設定 index.tsxをいじるだけ

npm辺りの設定はしなかったですね。

プロダクトコード

index.tsx
import { useEffect, useState } from 'react';
import Footer from '../component/footer'
import Header from '../component/header'



export default function Home() {
	ApiFetch();
	return (
		<>

		</>
	)
};


export const ApiFetch = () => {
	const [stones, setStone] = useState([]);

	useEffect(() => {
		// APIをfetchする(呼び出す)
		fetch("http://localhost:5000/api/products", { method: "GET" })
			// レスポンスのデータ形式をjsonに設定
			.then((res) => res.json())
			// APIから渡されるレスポンスデータ(data)をstateにセットする
			.then((data) => {
				setStone(data);
			});
	}, []);
}

動作確認

GoogleChromeの検証のNetWworkで確認
Apiが呼ばれたことを確認できました。

image.png

エラーパターン

@CrossOriginがない場合

PostmanではOKになるが、 Next.js側でレスポンスがエラーになる。googleの検証機能で確認。

error.message
Access to fetch at 'http://localhost:5000/api/products' from origin 'http://127.0.0.1:3000' 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.

画像
image.png

SpringSecuirty側でcorを設定する。

SecurityConfig.java

http.cors().disable()

→エラー解消せず
Springmvc側を設定する必要があり。
今回の場合は認可しなくても使えるApiだから?(わからん)

参考

Next.jsで外部APIを叩く3つのパターン

SpringBoot CORSの設定

SpringSecurity cor

2
2
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
2
2