blocked by CORS policy ionic to laravel

Viewed 153

Hello I created an ionic project and I am posting values via ajax to laravel backend (laravell is hosted by MAMP on the background), Whenever I am trying it by postman it's working correctly with a code 200

postman

But whenever I am trying it with my ionic project the code is here

function submitAxiosFormPost(e: React.FormEvent<HTMLInputElement>) {

    //? e: React.FormEvent<HTMLInputElement>

    // e.preventDefault();

    axios.post('http://localhost:8888/api/register', {
      name: username,
      email: email,
      password: password,
      password_confirmation: passwordConfirm
    })
      .then(function (response) {
        console.log(response);
          window.localStorage.setItem('profile', JSON.stringify(response.data.user));
          window.localStorage.setItem('token', JSON.stringify(response.data.access_token));
      })
      .catch(function (error) {
        console.log(error);
        // console.log("ERRRR:: ", error.response.data);
      });

    // name:Nairi7,
    // email:hnairiareg7@gmail.com,
    // password:Nairi7,
    // password_confirmation:Nairi7,


    console.log(`Username: ${username}\nEmail: ${email}\nPassword: ${password}\nPasswordConfirm: ${passwordConfirm}`);
  }

it's bringing this error

error

2 Answers

Your Ionic code isn't the problem here. Rather, it's your backend.

The problem has to do with web browsers limiting access to servers with CORS enabled. Web browsers only allow requests to web servers with CORS enabled for security reasons, so malicious sites do not read your data. Below is a link from Mozilla that talks more about CORS:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

I'm not 100% sure what your backend code is, as I'm not familiar with Laravel, so I can't guide you on how to enable CORS for your backend. However, I'm attaching a link which has instructions on enabling CORS for whatever your backend may be (I think Laravel uses PHP, so you might want to check that):

https://enable-cors.org/server.html

Once you enable CORS on your backend, you should be good to go.

Related