Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

php - ''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>
    )   
}
question from:https://stackoverflow.com/questions/65626067/access-control-allow-origin-header-is-present-on-the-requested-resource

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...