ごっそログ

勉強したことなどを書いていきます

Nuxt 3+Spring BootでREST API #9 NuxtからHTTPリクエストを送る

目次

  • フロントの実装
  • APIサーバの実装
  • 試運転

フロントの実装

<script setup lang="ts">
const onClick = async () => {
  const uri = "http://localhost:8080/hello";
  fetch(uri, {
    method: "GET",
    redirect: "follow",
  })
    .then((response) => {
      return response.json();
    })
    .then((json) => {
      console.log(json.message);
    })
    .catch((err) => {
      console.error(err);
    });
};
</script>
<template>
  <div>
    <button @click="onClick()">Hello</button>
  </div>
</template>

ボタンを配置し、クリック時にAPIリクエストが飛ぶようにする。
後々環境変数から読み込むようにしたいが、ひとまずlocalhostをハードコード。

APIサーバの実装

リクエストを受け取り、挨拶を返すコントローラクラス。

package com.sample.api.controller;

import com.sample.api.controller.out.GetOut;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("hello")
@RequiredArgsConstructor
@CrossOrigin
public class HelloController {

    @RequestMapping(method = RequestMethod.GET)
    public GetOut sayHello() {
        return new GetOut("Hello, client");
    }
}

試運転

ボタンを押下するとAPIサーバからレスポンスが返却された。