Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios: getting two requests OPTIONS & POST

I'm trying to post data. Everything works fine, but I don't know why I'm getting two requests OPTIONS & POST

POST: enter image description here

OPTIONS: enter image description here

Here's the code:

const url = 'http://rest.learncode.academy/api/johnbob/myusers';  export function postUsers(username, password) {     let users = {         username,         password,     };     return{         type: "USERS_POST",         payload: axios({             method:'post',             url:url,             data: users,         })             .then(function (response) {                 console.log(response);             })             .catch(function (error) {                 console.log(error);             })     } } 
like image 667
Liam Avatar asked Jan 15 '18 00:01

Liam


People also ask

How do I create multiple Axios requests?

Since axios returns a Promise we can go for multiple requests by using Promise. all , luckily axios itself also ships with a function called all , so let us use that instead and add two more requests. Again we define the different URLs we want to access.

Which method is used to make multiple concurrent requests using Axios?

all is a helper method built into Axios to deal with concurrent requests. Instead of making multiple HTTP requests individually, the axios. all method allows us to make multiple HTTP requests to our endpoints altogether.

How do I avoid the same request for multiple times to the server?

You can't stop the user from resubmitting a new request with the same ticket, but you can reject it on the server side, with a "Duplicate request" error. Right, but people do that on purpose - submit a form, press back because they know they need to correct something, submit form again.


1 Answers

Non-simple CORS requests via AJAX are pre-flighted. Read more about it here. This is a browser behavior and nothing specific to axios. There's nothing inherently wrong with this behavior and if it's working for you, you can just leave it.

If you insist on getting rid of it, there are a few ways you can go about:

  1. You can set Access-Control-Allow-Origin: * on your server to disable CORS.

  2. Make your CORS request a simple one. You will have to change the Content-Type header to application/x-www-form-urlencoded or multipart/form-data or text/plain. No application/json.

I'd say just leave it as it is if the OPTIONS request is not blocking you.

like image 107
Yangshun Tay Avatar answered Sep 27 '22 23:09

Yangshun Tay