Home > database >  Error on submit form with data in angular
Error on submit form with data in angular

Time:12-29

I tired to submit form data but getting json decode error from laravel api. I don't have access of laravel api side. When i am trying to submit it from swagger it works fine.

curl -X 'POST' \
  'https://example.com/create-reference' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer 883|DuNTAVq5Yl2FbeNEpWMk64dpiF0z8Nem1QG0fHUo54545' \
  -H 'Content-Type: multipart/form-data' \
  -F '[email protected];type=application/pdf' \
  -F 'reference={
  "contact_person": "Dalia Kadoch",
  "email": "[email protected]",
  "phone_number": "7821503357",
  "address": "Heriot House, Heriot Road, Chertsey, KT16 0DT",
  "company_name": "The Big Word",
  
}'

When i tried to submit it from angular my form body look like this and getting error.

    {
     "file" : "tes",
     "reference" : {
  "id": 1,
  "contact_person": "Dalia Kadoch",
  "email": "[email protected]",
  "phone_number": "7821503357",
  "address": "Heriot House, Heriot Road, Chertsey, KT16 0DT",
  "company_name": "The Big Word",
  "document_url": "https://image.com/image.jpeg"
} }

But I am getting json.decode() error from laravel.

json_decode(): Argument #1 ($json) must be of type string, array given"

CodePudding user response:

The swagger/curl request is submitting FormData with two fields named file and reference.

From the curl manual:

-F/--form <name=content>

(HTTP) This lets curl emulate a filled in form in which a user has pressed the submit button. This causes curl to POST data using the content-type multipart/form-data according to RFC1867. This enables uploading of binary files etc. To force the 'content' part to be be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the letter <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.

In your Angular approach, it looks like you are submitting a JSON object with the file and reference fields, but a JSON object is not FormData.

You can learn how to submit FormData in the following Stack Overflow post: How to send form data in a http post request of angular 2?

  • Related