This question might seem very easy to someone use to Yii2 API and React Js. I am quite new combining this technology.
I have a Yii2 API with the behaviors configured as shown here
public $serializer = ['class' => 'yii\rest\Serializer','collectionEnvelope' => 'items',];public static function allowedDomains(){ return ['*' // star allows all domains'http://localhost:3000', ];} public function behaviors() { return array_merge(parent::behaviors(), [ // For cross-domain AJAX request'corsFilter' => ['class' => \yii\filters\Cors::className(),'cors' => [ // restrict access to domains:'Origin'=> static::allowedDomains(),'Access-Control-Request-Method' => ['POST','GET','PUT','OPTIONS'],'Access-Control-Allow-Credentials' => false,'Access-Control-Max-Age' => 3600,// Cache (seconds)'Access-Control-Request-Headers' => ['*'],'Access-Control-Allow-Origin' => false, ], ], ]); }
when I use fetch request on this API using GET, It works perfectly well and returns the data to my reactjs frontend.
Now, I am trying to implement a signup to my application where I need to send data from my frontend using POST to my API.(I have implemented my signup action and it works well with postman.) When I try to make a post request to this API, I get the error , (CORS header ‘Access-Control-Allow-Origin missing) on my console. Below is my Reactjs request and I do not really know what I am missing. Any help on this will be greatly appreciated.
//this function is to save data to the APIsaveUser = (user) => { fetch(URL_SIGNUPUSER, { method: 'post', mode: "cors", headers: {'Accept': 'application/json','Content-Type': 'application/json', //'Access-Control-Allow-Credentials': "*" }, body: JSON.stringify({ name:user.name, username:user.username, email:user.email, password:user.password, }) }).then(res=>res.json()) .then(()=>{ this.setState({ user: { name:'', username:'', email:'', password:'', confirm_password:'', }, success:true, error:false }) });}