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.
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.
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.
//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.
http://localhost:3000/ When you access ...
The response value of the API is displayed on the screen.
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