Reputation: 1469
I have a login form (Username and Password) written in a React JS environment; the form consumes a REST API that contains the user credentials. I'm using the Fetch method to consume the API, but it errors out. I need to access the service via POST, but when I check (via chrome console - Network tab ) how my application is accessing the service, it states that the request method used is GET. How do I modify my code to access the form using post? Here is my code snippet I'm using to consume the web APT:
class Login extends Component {
//constructor
constructor() {
super();
this.state={
data: [],
}
}
//componet did mount method
componentDidMount(){
return fetch('http://myjson.com/file')
.then((response)=>response.json())
.then((responseJson)=>
{
this.setState({
data:responseJson.token
})
console.log(this.state.data)
})
}
I researched using the request.method but I'm uncertain how to implement it into the code. Could I get some help with this please? ...thanks in advance
Upvotes: 0
Views: 16161
Reputation: 2170
fetch('http://myjson.com/users/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'userName',
password: 'pwd',
})
})
Here is fetch docs
componentDidMount(){
return fetch('http://myjson.com/users/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'userName',
password: 'pwd',
})
})
.then((response)=>response.json())
.then((responseJson)=>
{
this.setState({
data:responseJson.token
})
console.log(this.state.data)
})
}
Upvotes: 3