Reputation: 59
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 :
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>
)
}
Upvotes: 0
Views: 3435
Reputation: 79
Just add these to your .php file and it should do the trick:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: 'X-Requested-With,content-type'");
header("Access-Control-Allow-Methods: 'GET, POST, OPTIONS, PUT, PATCH, DELETE'");
Or you could use a Chrome plugin like 'Moesif Origin & CORS Changer'
Upvotes: 3