0

I am trying to post data to my api via fetch. The post is working and my api is receiving it, but the data is not passing and everything is returned as null. What am i missing and is there anything i can improve with my current way of trying to do it?

HTML:

<form id="reportForm">
      <input class="name" id="name" type="text">
      <input class="phone" id="phone" type="tel">
      <input class="email" id="email" type="email">
</form>

Javascript:

document.getElementById('reportForm').addEventListener('submit', postData);

 function postData(event){
            event.preventDefault();

            let name = document.getElementById('name').value;
            let phone = document.getElementById('phone').value;
            let email = document.getElementById('email').value;

            let reqBody = {
              name: name,
              phone: phone,
              email: email
            };

            console.log("working");

            fetch('http://localhost:8888/api/report', {
              method: "POST",
              headers: {'Content-Type':'application/x-www-form-urlencoded'},
              body: JSON.stringify(reqBody)
            }).then((res) => res.json())
            .then((data) =>  console.log(data))
            .catch((err)=>console.log(err))
        }

API after posting data.

"data": [
{
  "report_id": 1,
  "user_id": null,
  "name": "null",
  "phone": "null",
  "email": "null"
}
]
user9294038
  • 141
  • 1
  • 10
  • 1
    "_everything is returned as null_" You didn't show us the code that actually creates the response so we can't know why it does that. – takendarkk May 24 '18 at 18:46

1 Answers1

0

The code sets the Content-Type to URL Encoded but the body is a JSON string. Try updating the Content-Type to application/json. Refer to this previous question. What is the correct JSON content type?

Joey Guerra
  • 596
  • 6
  • 11
  • I tried doing that but im getting the error "Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.". When im posting data to the api via postman im using x-www-form-urlencoded and its working properly – user9294038 May 24 '18 at 18:56
  • The error response has to do with CORS (https://enable-cors.org/server.html). Sounds like you're web service needs to allow Cross Origin Requests. – Joey Guerra May 24 '18 at 19:08