vendredi 17 mai 2019

how can i pass data in body from axios to my api

i was built test api by laravel 5 and i want to hit on this api using javascript ( axios ) library .. but all attempts not succeed because the body not received to backend i try some axios format but no succeed :( .. this is my backend code :

public function store(Request $request)
{ 
    $validator = Validator::make($request->all(), [
        'test_name' => 'required',
        'test_age' => 'required',
    ]);


    if ($validator->fails()) {
        return response()->json(['error'=>$validator->errors()],422);
    }

    $test = new Test;
    $test->test_name = $request->test_name;
    $test->test_age = $request->test_age;
    $test->save();

     return new TestResource($test);}

Javascript code :

const data = { 'test_age': 13 , 'test_name': 'Ahmad' };
 const url = "https://testDomain.com/api/tests";
axios.post(url, data )
.then(resp => {
        console.log(resp);
    })
.catch(error => {
        console.log(error);
    });

sometimes when returned the $request->all(); the backend returned nothing and sometimes return json has all data sent , but validation not read it any help please :(

  • I tried hit on the api from postman and the request received and data added successfully .


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire