alexander janet alexander janet - 2 months ago 26
React JSX Question

Can't connect react.js login to SpringBoot app

I am trying to call REST endpoints on one application (spring-boot) from another (reactjs). The applications are running on the following hosts and ports.



I am trying to send the login info from reactjs to spring-boot but without success.

Reactjs:

import React from 'react';


export default class Login extends React.Component {
constructor() {
super();
this.state = {
login:"",
password:""
};

this.handleChange = this.handleChange.bind(this);

}

handleChange() {
this.setState({login: this.state.login});
}


render() {

return (
<form role="form">
<div>
<input type="text" name="login" onChange={this.handleChange} />
<input type="password" name="password"/>
</div>
<button onClick={this.login.bind(this)}>Login</button>
</form>
);
}


login () {


var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var url = "http://localhost:8080/test/login"
xmlhttp.open("POST", url );
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({login: this.state.login}));
}
}


and Spring-boot:

@CrossOrigin(origins = "http://localhost:9000")
@RequestMapping(value = "/test/login")
public Boolean testLogin(@RequestParam String login) {
if ( login.equals ("ajt"))

return true;
else {
return false;
}
}


I can see that the two apps are connecting for even though reactjs gives me error 400, when I submit, the console of the Spring-boot app tells me:

Resolved exception caused by Handler execution: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'login' is not present


I can only assume that from the Spring-boot side, it cannot translate what ever is sent via react.js.

ps: bear with me, I have been coding for about 6 months.

Answer

I knew this looked familiar. Sorry my last answer didn't fix all your issues.

Your current problem is here;

public Boolean testLogin(@RequestParam String login) {

Should be

public Boolean testLogin(@RequestBody String login) {

EDIT:: Second problem.

Your handleChange function isn't taking in any values! It should look more like this;

handleChange(value) {
    this.setState({login: value});
}

When your input field calls this function, it needs to pass a value from the input into the state. Your current code is essentially the same as this;

this.state.login = this.state.login;

Which obviously isn't going to get you anywhere.

Try that change. If it still does not work, be sure you open your dev-tools in your browser and step through the code line by line to be sure it is executing and storing the values you want it to.

Comments