简体   繁体   English

如何将数据发布到api

[英]How to post data to api

I am trying to post data to my api via fetch. 我正在尝试通过提取将数据发布到我的api。 The post is working and my api is receiving it, but the data is not passing and everything is returned as null. 该帖子正在运行,我的api正在接收它,但数据未传递,并且所有内容均返回null。 What am i missing and is there anything i can improve with my current way of trying to do it? 我想念的是什么?我目前的尝试方式有什么可以改善的?

HTML: 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: 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. 发布数据后的API。

"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. 该代码将Content-Type为URL Encoded,但是主体是JSON字符串。 Try updating the Content-Type to application/json . 尝试将Content-Type更新为application/json Refer to this previous question. 请参考上一个问题。 What is the correct JSON content type? 什么是正确的JSON内容类型?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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