Failed to send JSON from next.js to API server laravel

40 views Asked by At

I have a problem with sending JSON data to the API server Laravel, this is my code, I take some value from the radio button it has a string array, then I change it into an int array, then into JSON.stringify, but it does not work, this is my code for the handleSubmit radio button

  const handleRadioChange = (e) => {
      const value = e.target.value
      const isChecked = e.target.checked;
      if (isChecked) {
        setSelectedValues((prevValues) => [...prevValues, value]);
      } else {
      setSelectedValues((prevValues) =>
       prevValues.filter((prevValue) => prevValue !== value)
      );
    }
  }

  const handleSubmit = async (e) => {
    e.preventDefault();

    const formData = new FormData();

    const selectedValuesString = selectedValues.join(',')
    setValuesarray(selectedValuesString.split(','));

    const integerValues = valuesarray.map(value => {
    const intValue = parseInt(value, 10);
    if (isNaN(intValue)) {
      console.log(`Error: Cannot parse value '${value}' to an integer`);
    }
    return intValue;
    });

    setValuesint(integerValues);

    console.log("valuesint:", valuesint);

    setValuesintJson(JSON.stringify(valuesint));
    console.log("valuesjson:", valuesintJson);

    formData.append('jawaban_soal', valuesintJson);

    await axios.post(`${process.env.NEXT_PUBLIC_API_BACKEND}/api/hasil`, formData)
    .then(()=> {
      Router.push(`/Ujian/${ujian.id}`)
        })
    .catch((error)=> {
      setValidation (error.response.data)
      })

      console.log("formData:", formData);
    }

and this is my code for the API server controller

public function simpanJawaban (Request $request) {

    $validator = Validator::make($request->all(),
    [
      'jawaban_soal' => 'required|array',
    ]);


    $jawabanSoal = $request->input('jawaban_soal');
    $total = array_sum($jawabanSoal);

    $hasil = hasil::create([
      'total' => $total,
    ]);
  return new PostResource (true, 'stored', $hasil);
  }

When I use Postman using header = application/json and raw JSON, it work POSTMAN (https://i.stack.imgur.com/jL9bf.png)

0

There are 0 answers