[英]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.