繁体   English   中英

如何将数据发布到api

[英]How to post data to api

我正在尝试通过提取将数据发布到我的api。 该帖子正在运行,我的api正在接收它,但数据未传递,并且所有内容均返回null。 我想念的是什么?我目前的尝试方式有什么可以改善的?

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。

"data": [
{
  "report_id": 1,
  "user_id": null,
  "name": "null",
  "phone": "null",
  "email": "null"
}
]

该代码将Content-Type为URL Encoded,但是主体是JSON字符串。 尝试将Content-Type更新为application/json 请参考上一个问题。 什么是正确的JSON内容类型?

暂无
暂无

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

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