Am tring to post data from React.js to localhost insert.php file. When i submit the form from reactjs it gives me error on console Error is :
- Access to XMLHttpRequest at 'http://localhost/reactphpdemo/connect.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
- xhr.js:177 POST http://localhost/reactphpdemo/connect.php net::ERR_FAILED
- createError.js:16 Uncaught (in promise) Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:84)
Here is my code
import React, { Component } from 'react';
import axios from 'axios';
export default class Insert extends Component {
constructor(props){
super(props);
this.onSubmit = this.onSubmit.bind(this);
this.state={
first_name:'',
last_name:'',
email:''
}
}
onSubmit(e){
e.preventDefault();
const obj = {
headers:{'Access-Control-Allow-Origin':'*'},
first_name:this.state.first_name,
last_name:this.state.last_name,
email:this.state.email,
};
axios.post('http://localhost/reactphpdemo/insert.php',obj).then(res=>console.log(res.data));
this.setState({
first_name:'',
last_name:'',
email:''
})
}
render() {
return (
<form onSubmit={this.onSubmit}>
<div class="form-group">
<input type="submit" value="Register User" class="btn btn-primary" name="name" />
</div>
</form>
)
}