简体   繁体   中英

How to post data to api

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"
}
]

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM