Sending a post request through Axios is generating an empty RequestBody in Spring-Boot backend. Works in Postman but not through Axios post request

Vineet B Nath :

I have a react frontend and a spring backend. I have rest service for the backend that takes a summarizerData as an input and returns the same as output. I have a form which takes a textarea input and submit button. When sending a post request through axios i am getting an empty object. I have tested the api through postman but when submitting it through axios, i am getting a 500 internal error.

I have enabled CORS in the RestController.

Please let me know what is the issue 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

@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.

I am a react beginner so pls let me know of any mistakes.

Thanks

Jakub Licznerski :

The problem is that you unnecessarily wrap summarizerData and headers with object constructor operator ({}). 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": {
    "paragraph": this.state.paragraph,
    "creationDate": "2019-03-10T00:58:23",
    "summarizedSentences": null
  }
}

Which cannot be mapped to SummarizerData in your backend. You can use Devloper Tools (Chrome, Firefox) to investigate your HTTP calls. It will allow you e.g. to see what is actually sent in request body, see request and response headers and it's values etc.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159261&siteId=1