Post method in ionic 3

ı have laravel json api and works well when ı made auth in laravel post method work nice. but in ionic my codes didnt work.

this is provider

 postData(credentials, type){

    return new Promise((resolve, reject) =>{
      let headers = new Headers({
        'Content-Type' : 'application/json'
      });
      let options = new RequestOptions({ headers: headers });
      
    this.http.post(apiUrl+type, JSON.stringify(credentials), {headers: headers}).
      subscribe(res =>{
        resolve(res.json());
      }, (err) =>{
        reject(err);
      });

    });

  }

signup.ts

export class SignUpPage {
  resposeData : any;
  userData = {"full_name":"", "password":"","email":"","name":""};
 

  constructor(public navCtrl: NavController, public authProvider:AuthProvider, 
    public alertCtrl: AlertController ,  public toastCtrl:ToastController
    ) {
  }

signup() {
    if(this.userData.full_name && this.userData.password && this.userData.email && this.userData.name){
      //Api connections
    this.authProvider.postData(this.userData, "signup").then((result) =>{
    this.resposeData = result;
    if(this.resposeData.userData){
      console.log(this.resposeData);
      localStorage.setItem('userData', JSON.stringify(this.resposeData) )
      this.navCtrl.push(HomePage);
    }
    else{
      this.presentToast("Please give valid username and password");
    }
    
    }, (err) => {
      console.log("error");
    });
  }
  else {
    console.log("Give valid information.");
  }
  
  }

  login() {
    this
      .navCtrl
      .push(SignInPage);
  }

  presentToast(msg) {
    let toast = this.toastCtrl.create({
      message: msg,
      duration: 2000
    });
    toast.present();
  }

and when ı make auth in ionic ı am getting this error.

access to XMLHttpRequest at ‘http://…8000/api/signup’ from origin ‘http://localhost’ 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.

so please help me.

If you are using chrome then add this extension : Allow-Control-Allow-Origin

then add host URL(ex. http://localhost:8100/) in extension and refresh if stay same issue remove URL from chrome and refresh your page

corss-Origin extension works olny localhost when you are publish your app your api dosent work well

make sure cross origin allow in your laravel api
@Tubiss

but other data which in the json is display on the chrome.I have problem only signup and signin

Hi, you are having a CORS issue, since you are using Laravel install Laravel CORS Package this will resolve your CORS issues and your app will be fine

Still same error polyfills.js:3 POST localhost/api/student 405 (Method Not Allowed)

Access to XMLHttpRequest at ‘localhostapi/student’ from origin ‘http:/localhost’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

please help me .

hi, after installing the package, can i see your config/cors.php content?

config/cors.php

<?php



return [





    'supportsCredentials' => false,



    'allowedOrigins' => ['*'],


    'allowedHeaders' => ['Content-Type', 'X-Requested-With'],


    'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT',  'DELETE']


    'exposedHeaders' => [''],


    'maxAge' => 0,
];

So Access-Control-Allow-Origin is needed in the allowedHeaders.

Update your allowedHeaders to ['Content-Type', 'X-Requested-With', 'Access-Control-Allow-Origin'] to allow it.

Or alternatively, update your header to ['*'] to allow all header

still same giving error. dont know where ı am wrong . I can make auth in the laravel login and my login info is inserted to database . But in the ionic ı always getting this error so please help me.

Hi, Please share more details so i can help

ok ı am going to explain what ı did.

ı made auth with different table(student table) instead of default user table.
And ı can make login in the laravel auth with student table and my info is inserted to database.
Everything is fine until now.

And ı have been insert some auth code in ionic app and ı cannot make login.
By the way my api works well because ı can pull json data and ı can display json data in the ionic app. But can not make post method.

Ok, confirm that the route you are trying to post to exist and you can post to it through Postman

looking at this 405, it means that the /student route does not allow POST method

yes ı cannot post in the postman

okay, that mean in your laravel api, you haven’t create a POST route. so do that first and try again

ı made a function as called store in the studentController

 public function store(Request $request)
    {
		
        $full_name = $request->full_name;
		$email = $request->email;
		 $password = $request->password;

        //
    }

and api.php

Route::post("/studentpost", "StudentController@store");

and in the postman when ı try its not giving error and giving nothing and ı checked my database its not inserted.

okay, good. looks like everything is fine now, in your store function insert the content into the db, then you will be able to see it

ı am not sure is it true. I made insert content db like this if its wrong please tell me.

	 public function store(Request $request)
    {
		
		 $student = new Student();
		
       $student->full_name = request(full_name);
 $student->email = request(email);
		 $student->password = request(password);
		 $student->save();

        //
    }

and when ı made this ı got the error from postman like this

ErrorException: Use of undefined constant full_name - assumed 'full_name' (this will throw an Error in a future version of PHP) in

Okay, follow the following steps

import this in your controller file

use Illuminate\Support\Facades\Hash;

then in your store method write:

$student = new Student();
$student->full_name = $request->full_name;
$student->email = $request->email;
$student->password = Hash::make($request->password);
$student->save();

return response()->json(['status'=>'success','message'=> 'Student Created']);

It should work now

Note: you dont save password as plain text, that is why you need to Hash it.