Ronak Bhatti
Ronak Bhatti

Reputation: 59

''Access-Control-Allow-Origin' header is present on the requested resource

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 :

  1. 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.
  1. xhr.js:177 POST http://localhost/reactphpdemo/connect.php net::ERR_FAILED
  2. 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>
    )   
}

Upvotes: 0

Views: 3435

Answers (1)

DenisDaniel707
DenisDaniel707

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

Related Questions