Я занимаюсь разработкой приложения для опросов, использующего Springboot Rest API и интерфейс ReactJS, и столкнулся с, казалось бы, неразрешимой проблемой. В моем приложении Springboot у меня есть bean-компонент Topi c, который записан следующим образом:
@Entity
public class Topic {
@Id
@GeneratedValue
private Long id;
private String question;
@NotNull
@Size(min=3, max=20)
private String topic;
@Column(precision=4, scale=1)
private double npm = 0;
@OneToMany(mappedBy = "topic")
private Set<Submission> submissions;
public Topic()
{
super();
}
public Topic(Long id, String topic, double npm)
{
super();
this.id = id;
this.setTopic(topic);
this.setNpm(npm);
}
public Long getID()
{
return this.id;
}
public void setId(Long id)
{
this.id = id;
}
/**
* @return the topic
*/
public String getTopic() {
return topic;
}
/**
* @param topic the topic to set
*/
public void setTopic(String topic) {
this.topic = topic;
}
/**
* @return the npm
*/
public double getNpm() {
return npm;
}
/**
* @param npm the npm to set
*/
public void setNpm(double npm) {
this.npm = npm;
}
/**
* @return the question
*/
public String getQuestion() {
return question;
}
/**
* @param question the question to set
*/
public void setQuestion(String question) {
this.question = question;
}
}
и класс репозитория:
@Repository
public interface TopicRepository extends JpaRepository<Topic, Long>{
@Transactional
@Modifying
@Query("UPDATE Topic SET npm = ?1 WHERE id = ?2")
public void updateNpm(double newNpm, long id);
@Query("SELECT topic FROM Topic")
public List<String> getTopics();
}
Наконец, мой класс Controller имеет вид следует (я опустил методы, которые не вызывают проблем):
@RestController
public class TopicResource {
@Autowired
private TopicRepository topicRepository;
@CrossOrigin
@PostMapping("/topics")
public void createTopic(@RequestBody Topic topic)
{
Topic savedTopic = topicRepository.save(topic);
}
}
В моем приложении React я делаю POST-запрос от следующего компонента Class:
import React, { Component } from 'react';
import './Styling/createsurvey.css'
class CreateSurvey extends Component {
constructor () {
super();
this.state = {
topic: '',
question: ''
};
this.handleTopicChange = this.handleTopicChange.bind(this);
this.handleQuestionChange = this.handleQuestionChange.bind(this);
//this.printState = this.printState.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleTopicChange(e) {
this.setState({
topic: e.target.value
});
}
handleQuestionChange(e) {
this.setState({
question: e.target.value
});
}
handleSubmit(event) {
event.preventDefault();
console.log(this.state.topic);
console.log(this.state.question);
fetch('http://localhost:8080/topics', {
method: 'post',
headers: {'Content-Type':'application/json'},
body: {
"npm": "0",
"topic": "Turkey",
"question": "How is life here",
"submissions": {}
}
});
}
render() {
return(
<div>
<form onSubmit={this.handleSubmit}>
<h2>Create a new Survey</h2>
<br></br>
<div className="form-group">
<label><strong>Enter the survery topic: </strong></label>
<br></br>
<input
className="form-control"
placeholder="Enter a cool topic to ask a question about"
align="left"
onChange={this.handleTopicChange}>
</input>
</div>
<div className="form-group">
<label><strong>Enter a survey question: </strong></label>
<br></br>
<textarea
className="form-control"
placeholder="Ask your question here. The customer will give an answer on a scale from 1 to 10."
align="left"
rows="3"
onChange={this.handleQuestionChange}>
</textarea>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">Submit Your Question</button>
</div>
</form>
</div>
);
}
}
export default CreateSurvey;
Я столкнулся со следующей ошибкой:
2020-03-03 01:15:17.862 DEBUG 17816 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : POST "/topics", parameters={}
2020-03-03 01:15:17.862 DEBUG 17816 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.recommend.me.springboot.rest.recommendme.topic.TopicResource#createTopic(Topic)
2020-03-03 01:15:17.867 DEBUG 17816 --- [nio-8080-exec-1] .w.s.m.m.a.ServletInvocableHandlerMethod : Could not resolve parameter [0] in public void com.recommend.me.springboot.rest.recommendme.topic.TopicResource.createTopic(com.recommend.me.springboot.rest.recommendme.topic.Topic): Invalid JSON input: Cannot deserialize instance of `com.recommend.me.springboot.rest.recommendme.topic.Topic` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.recommend.me.springboot.rest.recommendme.topic.Topic` out of START_ARRAY token
at [Source: (PushbackInputStream); line: 1, column: 1]
Может кто-нибудь указать, что я делаю неправильно с моей просьбой? Я перепробовал все формы JSON форматов запросов, но, похоже, ничего не работает.