◆ Get API created by Spring Boot from React

★ Introduction

I'm also studying Node.js and React in parallel with studying Spring, but the progress is slow probably because the front side is not good at it. As usual, it will be an article of work memo and study record.

★ What you want to do

Subject mom. ◆ Try to call the API in SpringBoot + gradle REST + JSON format Implement the process to call the API created in step 1 on the front side.

By the way, in business, we mainly develop APIs using the basic server side and our own framework. Even though I have the experience of implementing the process of calling the API from the batch, I have not had the experience of implementing the process of calling the API from the front side and the screen, so it was a good study.

★ API side (SpringBoot)

RestApiController.java


package com.example.sample.app.controller;

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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.sample.app.resource.BirthStone;

@RestController
@CrossOrigin(origins = "*") //★ Changes
@RequestMapping("api/sample")
public class RestApiController {
    
    @RequestMapping(value = "/getBirthStone", method = RequestMethod.GET)
    @ResponseBody
    public BirthStone getBirthStone() {
        BirthStone birthStone = new BirthStone("February", "amethyst", "purple");
        return birthStone;
    }
}

When actually calling from the screen ** "Blocked cross-origin request: Same-origin policy refuses to load remote resources under [* API URL](Reason: Missing CORS header'Access-Control-Allow-Origin'" ). [Details] "** What an error message was output to the console, so I thought it was an error with ** CORS **. I first learned the word CORS because I didn't study. I haven't figured it out yet, so I plan to study at a later date. I would like to write an article if I have the spare capacity.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/CrossOrigin.html

CORS can be controlled by adding the @CrossOrigin annotation. ʻOrigins` (Access-Control-Allow-Origin) is set to" * "(wildcard).

Start locally. The port is the default 8080.

★ Screen side (React)

//Project creation
create-react-app call_api_sample
//Move to project
cd  call_api_sample
// node-Install fetch
npm install --save node-fetch
//Server startup
npm start

I created a project and installed it because I wanted to use the Fetch API. Start the server. The default port is 3000.

App.js


import React, { Component } from 'react';
import fetch from 'node-fetch';
import './App.css';

class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      month: '',
      name: '',
      color: ''
    }
  }
  componentWillMount () {
    const URL = 'http://localhost:8080/api/sample/getBirthStone'
    fetch(URL, {mode: 'cors'})
    .then(res => res.json())
    .then(json => {
      this.setState({
        month: json['month'],
        name: json['name'],
        color: json['color']
      })
    });
  }

  render() {
    return <div className='App'>
      month: {this.state.month} <br />
      name: {this.state.name} <br />
      color: {this.state.color} <br />
    </div>
  }
}

export default App;

I thought about making another js file, but it was only a simple communication confirmation, so I rewrote App.js.

The month, name, and color are initialized (empty) with constructor.

The API is called by componentWillMount (process executed before component creation), and the response values are packed in month, name, and color. Set mode to'cors' to support CORS.

★ Execution result

http://localhost:3000/ When you access ...

WS000006.JPG

The response value of the API is displayed on the screen.

★ Reference

In writing this article, I referred to the following books and articles.

Node.js and React application development techniques for modern JS programmers

CORS Summary [JavaScript basics] Fetch API basics --KDE BLOG Enable fetch in Node.js Cheers for good work XMLHttpRequest, Hello fetch

Recommended Posts

◆ Get API created by Spring Boot from React
Get data with api created by curl command
[Spring Boot] Get user information with Rest API (beginner)
Try Spring Boot from 0 to 100.
Get started with Spring boot
Deploy the application created by Spring Boot to Heroku (public) ②
Deploy the application created by Spring Boot to Heroku (public) ①
Spring Boot: Restful API sample project
Get validation results with Spring Boot
Implement REST API in Spring Boot
Upgrade spring boot from 1.5 series to 2.0 series
Spring Boot starting from zero Part 2
Spring Boot starting from zero Part 1
02. I made an API to connect to MySQL (MyBatis) from Spring Boot
[Java] Get data from DB using singleton service in Spring (Boot)
Change Spring Boot REST API request / response from CamelCase to SankeCase
Get Flux result of Spring Web Flux from JS with Fetch API
Story when moving from Spring Boot 1.5 to 2.1
Changes when migrating from Spring Boot 1.5 to Spring Boot 2.0
Get account information by accessing Strava's API
Get "2-4, 7, 9" from [4, 7, 9, 2, 3]
03. I sent a request from Spring Boot to the zip code search API
[Spring Boot] How to get properties dynamically from a string contained in a URL
Get the class name and method name of Controller executed by HandlerInterceptor of Spring Boot
Use Thymeleaf text template mode from Spring Boot
Build Spring Boot project by environment with Gradle
Get Enum by reverse lookup from the contents
Create a web api server with spring boot
Spring Boot Memorandum
gae + spring boot
I created an api domain with Spring Framework. Part 2
Automatically map DTOs to entities with Spring Boot API
Hello World (REST API) with Apache Camel + Spring Boot 2
Customizer for Platform Transaction Manager added from Spring Boot 1.5
[Spring boot] I thought about testable code by DI
Customize REST API error response with Spring Boot (Part 2)
How to boot by environment with Spring Boot of Maven
Load an external jar from a Spring Boot fat jar
Customize REST API error response with Spring Boot (Part 1)