[英]Sending a post request through Axios is generating an empty RequestBody in Spring-Boot backend. Works in Postman but not through Axios post request
I have a react frontend and a spring backend. 我有一个React前端和一个Spring后端。 I have rest service for the backend that takes a summarizerData as an input and returns the same as output.
我为后端提供了休息服务,该服务将summaryrData作为输入并返回与输出相同的内容。 I have a form which takes a textarea input and submit button.
我有一个带有textarea输入和提交按钮的表单。 When sending a post request through axios i am getting an empty object.
通过axios发送发帖请求时,我得到了一个空对象。 I have tested the api through postman but when submitting it through axios, i am getting a 500 internal error.
我已经通过邮递员测试了该api,但是通过axios提交该api时,出现了500个内部错误。
I have enabled CORS in the RestController. 我已经在RestController中启用了CORS。
Please let me know what is the issue SummarizerData Pojo 请让我知道SummarizerData Pojo是什么问题
@Entity(name = "user_text_data")
@Getter
@Setter
@ToString
public class SummarizerData {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String paragraph;
@Column
private LocalDateTime creationDate;
@Transient
private List<Sentence> summarizedSentences;
public SummarizerData(){
}
public SummarizerData(String paragraph){
this.paragraph = paragraph;
this.creationDate = LocalDateTime.now();
}
}
TextSummarizerController TextSummarizerController
@RepositoryRestController
@RequestMapping("/api")
public class TextSummarizerController{
@Autowired
SummarizerDataRepository repository;
Logger logger = Logger.getLogger(TextSummarizerController.class.getName());
@CrossOrigin
@RequestMapping(method = RequestMethod.POST, value = "/summarize")
public @ResponseBody SummarizerData getSummarizerData(@RequestBody SummarizerData data ){
System.out.println("Returning Summarized Data");
SummaryTool summaryTool = new SummaryTool();
logger.info(data.toString());
repository.save(data);
data.setSummarizedSentences(summaryTool.startSummarization(data.getParagraph()));
return data;
}
}
React FrontEnd 反应前端
import React, { Component } from 'react';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Navbar from './components/Navbar';
import ParagraphEntry from './components/ParagraphEntry';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import axios from 'axios';
class App extends Component {
constructor(props){
super(props);
this.state = {
"summarizerData" : {},
"paragraph" : ""
} ;
}
onChange = (e) => {
this.setState({"paragraph" : e.target.value});
};
onSubmit= (e) => {
e.preventDefault();
var headers = {
'Content-Type': 'application/json'
}
const summarizerData = {
"paragraph" : this.state.paragraph,
"creationDate" : "2019-03-10T00:58:23",
"summarizedSentences" :null
};
axios.post('http://localhost:8080/api/summarize',{summarizerData}, {headers})
.then(res => console.log(res.data))
console.log(summarizerData);
}
handleClear = (e) => {
console.log(e);
e.target.value = "";
this.setState({"paragraph" : ""});
}
render() {
return (
<div className="App">
<Navbar />
<ParagraphEntry onChange = {this.onChange} onSubmit={this.onSubmit} handleClear = {this.handleClear} paragraph = {this.state.paragraph}/>
</div>
);
}
}
export default App;
Error logs 错误日志
Returning Summarized Data
2019-03-18 00:10:19.487 INFO 8336 --- [nio-8080-exec-5] c.n.t.s.rest.TextSummarizerController : SummarizerData(id=null, paragraph=null, creationDate=null, summarizedSentences=null)
2019-03-18 00:10:19.491 WARN 8336 --- [nio-8080-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1048, SQLState: 23000
2019-03-18 00:10:19.491 ERROR 8336 --- [nio-8080-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'creation_date' cannot be null
2019-03-18 00:10:19.495 ERROR 8336 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Column 'creation_date' cannot be null
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:970) ~[mysql-connector-java-8.0.15.jar:8.0.15]
The highlight in the above is SummarizerData with all fields as null. 上面的重点是SummarizerData,所有字段均为null。
I am a react beginner so pls let me know of any mistakes. 我是一名反应灵敏的初学者,所以请让我知道任何错误。
Thanks 谢谢
The problem is that you unnecessarily wrap summarizerData
and headers
with object constructor operator ( {}
). 问题是您不必要使用对象构造函数运算符(
{}
)包装summarizerData
和headers
。 You have already created the objects before and this should resolve your issue: 您之前已经创建了对象,这应该可以解决您的问题:
axios.post('http://localhost:8080/api/summarize', summarizerData, headers)
What {summarizerData}
does is create an object like this: {summarizerData}
所做的是创建一个像这样的对象:
{
"summarizerData": {
"paragraph": this.state.paragraph,
"creationDate": "2019-03-10T00:58:23",
"summarizedSentences": null
}
}
Which cannot be mapped to SummarizerData
in your backend. 无法在后端将其映射到
SummarizerData
。 You can use Devloper Tools ( Chrome , Firefox ) to investigate your HTTP calls. 您可以使用Devloper工具( Chrome , Firefox )来调查HTTP调用。 It will allow you eg to see what is actually sent in request body, see request and response headers and it's values etc.
例如,它将允许您查看请求主体中实际发送的内容,请求和响应标头及其值等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.