fetchを使用してSpringのコントローラにリクエストを送信するサンプルを示す。
以下は、JavaScriptのfetchを使用して
SpringコントローラにGETリクエストを送信する例。
Springのコントローラクラス:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@GetMapping("/action")
@ResponseBody
public String performAction() {
return "Spring Controller Action Executed";
}
}このコントローラはGETリクエストを受け付け、”Spring Controller Action Executed”というテキストを返す。
JavaScriptでfetchを使用してこのコントローラにリクエストを送信する:
fetch('/action') // Springのコントローラへのリクエスト
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text(); // レスポンステキストを取得
})
.then(data => {
// レスポンステキストを処理
console.log(data); // "Spring Controller Action Executed" が表示される
})
.catch(error => {
// エラーハンドリング
console.error('Fetch Error:', error);
});このコードでは、fetchを使用して/actionエンドポイントにGETリクエストを送信し、
コントローラの応答を処理している。
成功した場合、コントローラの応答テキストがコンソールに表示される。
Springのコントローラが別のHTTPメソッドをサポートしている場合、fetchの第二引数でmethodオプションを指定して適切なメソッドを使用できまる。
(例: POST、PUTなど)。

