Problem with CORS - Preflight (get works, post does not)

Asked

Viewed 1,981 times

-1

Does anyone know how I can solve this CORS problem? Because honestly I tried a lot and I could not, I already put in the backend (php) ACCESS-CONTROL-ALLOW-ORIGIN * and others, even so the error persists, only for posts:

public static function HTTPResponseSet($httpStatusCode) {
  header('Access-Control-Allow-Origin: *');
  header("Content-Type: application/json; charset=utf-8");
  http_response_code($httpStatusCode);

  // Allow from any origin
  if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
  }

  // Access-Control headers are received during OPTIONS requests
  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
      header("Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS");         
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
      header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
      // header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding");
    exit(0);
  }
}

And yes, I’m calling the function. I do other project requests on localhost and they work, but using Vue on port 8080 with Axios, and the project on localhost/project does not work.

Code request: `methods: { save() { Let client = { name: this.form.name, Description: this.form.Description, }

  axios.post('http://localhost/usios_planner/project/public/client/create', client)
  .then(response => {
    window.console.log('Ok', response)
  })
  .catch(error => {
    window.console.log('Error: ', error);
  });

  this.$store.state.clients.push(client)
  window.console.log('Client: ',client)

  this.dialog.show = true;
}

},`

Error print: https://prnt.sc/rzzb6i Error: Failed to load Resource: the server responded with a status of 422 (Unprocessable Entity) client:1 Access to Xmlhttprequest at 'http://localhost/usios_planner/project/public/client/create' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

I’m using: PHP in backend, Vuejs in Front and Axios in Vue.

NOTE: The above code to activate CORS worked for requests I do on localhost/pasta_do_project, but on Vue (localhost:8080) I have the error in question.

  • 1

    Okay, there’s been a misunderstanding on my part. I thought William entered the topic just to talk about it and not to "help," so all this fuss. But soon after he answered below the solution. I’ve said I’m sorry and I’ve thanked you, and I was wrong in this way because some people get into topics and just talk about things like that and they don’t help. I have seen many topics here so anyway thank you both. I will not post more code images.

  • 3

    Quiet, I just want you to understand that commenting on how to format questions is also a way to help. Not in the sense of "help directly in the problem", but yes "help the site to become more organized". And both are valid, since once posted here, the question ceases to be only yours and becomes "of all", and so we’re kind of "boring" in leaving everything neat :-)

  • 2

    @Deyvid, In the case William did the guidance and gave the answer. But look at my case, I choose instead twenty questions that are closed or in the process of being closed, I analyze them case by case and leave the guidelines for each author to improve and clarify. Of those twenty I can answer about five at a time the other fifteen members of the community will present the answers.

  • 2

    So if the person passes and leaves an orientation does not mean that it is chata She’s just showing you the way to get a response and if she apparently did the guidance but didn’t answer it she’s probably stuck in another response or analysis queue.

1 answer

2


Preflight almost always indicates what has not been configured properly, its own message:

... It does not have HTTP ok status.

The HTTP ok refers to HTTP code 200, which means that when you sent a reply to the initial request on OPTIONS was not sent with code 200, probably with another code and probably even not being POST and yes OPTIONS he is trying to execute the POST.

In Preflight always two requests will be sent:

  1. The initial OPTIONS request, which is generated by the browser
  2. The normal request when there is an unexpected change, such as on request headers that are not common, for example changed the content-type of Axios or $.ajax

Probably this will solve:

  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
      header("Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS");         
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
      header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
      // header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding");
    exit(0);
  }

But there is no way to affirm, because you created a whole environment of treatment of your HTTP and we do not know how the status was modified, so what I can say is that in OPTIONS always send the:

HTTP/1.1 200 OK

That in PHP you can write with http_response_code(); or with header();

  • Okay, thank you. Now yes it matches. Thank you very much, I will test and if it works I will mark as best answer.

  • @Deyvid ok, any doubts comment here.

  • I thought you were just here to talk about the image. But what Voce said worked, so I apologize and thank you for the tip about both HTTP and the image, some get into topics just to answer things like that. Anyway, it worked, but the Axios post is not going, I’m returning the post and returns an array(0), follows the code of the two https://pastebin.com/ZXXDuMVSattempts

  • 3

    @Deyvid the comments field is yes to give guidance, you understand or not, we have a good site and thanks to follow certain tips, even if a person other than me had come here just to guide you, you should always accept the tips, because they help not only you, but the site’s community as well ;)

  • 1

    @Deyvid I would like an addendum. Closure, editing or a critique of the question format are not punishments or footholds. These are ways that the community has to regulate and improve the quality of the content presented here on the site. More experienced users go through the questions identifying and guiding younger users how to improve the way to expose their doubts...

  • 1

    ...Some people get annoyed but I assure the goal of guidance is to increase the chances of user to get faster a good response. As there are many questions received daily sometimes a user makes the guidance and others pass by answering the improved questions. If in the future on any other issue you have a note follow it because as soon as you edit the question it is in evidence and another user, or the same, will go through it and give you a feedback.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.