0

I have an Array, i want to get all values one by one from Array and post value using axios to rest-api django

In Django i have model:

class Cars(models.Model):
    car = models.CharField(max_length=100)

i want to add data in my model from axios post here is my array, from this array i want to get value and add in to my model one by one on single submit,

let cars = [
   ["Saab", "Volvo", "BMW"],
   ["Toyota", "Alto", "Civic",]
]

i have try like this,

  handleFormSubmit = event => {
     event.preventDefault();
    for (var i = 0; i < cars.length; i++) {
       axios.post('myURL',{
            car: car[i]
        })
        .then(res => console.log(res))
        .catch(err => console.log(err));
      }
    }

and after on submit i got Error: "Request failed with status code 400", when i make axios post outside the loop it is fine, but i want to add multiple data from an array.

2 Answers 2

1

400 error means that:

Bad Request. Your browser sent a request that this server could not understand.

Try to use the forEach function in your snippet. Sth like this:

 handleFormSubmit = event => {
     event.preventDefault();
     cars.forEach(car =>
       axios.post('myURL',car)
        .then(res => console.log(res.data))
        .catch(err => console.log(err));
      }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

you declared variable as cars and and using car in loop .

  • axios.post('myURL',{ car: cars[i] })

try this change

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.