javascript - 表单提交值给出 null - mongoose 和 express js
问题描述
我正在尝试使用 express 将数据从基本的 html 表单发送到 mongodb。但是当我发布它时它给了我null。
我使用了以下架构:commentname:String。
这是HTML:
<form id="form" onsubmit="return false;">
<input type="textbox" id="cmt-1" placeholder="comment here"/>
</form>
<button type="button" onclick="submit()" class="submit">
submit
</button>
JS:
var cmt = document.getElementById('cmt-1').value;
var comment = {commentname: ''};
comment = {commentname: cmt};
function submit () {
async function postData (url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'same-origin',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData(
'https://realtime-comt-system-100.glitch.me/comments/add',{comment}
)
.then(data => { console.log(data); });
}
我错过了什么?
解决方案
只需尝试此代码,但请检查我输入的网址。不要放整个 url 只放路径名。也把这段代码复制和粘贴,html和java脚本都把它们都拿走了,因为我改变了它们
var form = document.getElementById('form');
form.addEventListener('submit', async(e) => {
e.preventDefault();
let cmt = form.cmt.value;
let data = {commentname: cmt};
const response = await fetch('/comments/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(res =>{
console.log(res)
}).catch(err){
console.error(err)
}
})
<form id="form">
<input type="textbox" id="cmt-1" name='cmt' placeholder="comment here"/>
</form>
<button type="submit" onclick="submit()" class="submit">
submit
</button>
推荐阅读
- javascript - JS 不等待 Promise 实现?
- ios - 设置 setCenterWindow + NappDrawer 时出现崩溃问题
- php - Wordpress 简码返回另一个 php 页面
- javascript - 将 json 中的标题添加到 html 中的文本内容
- windows - 如何在 Windows 中模拟外部 TCP 流量?
- r - 将数据框的行值与其对应的值匹配
- java - 日期配置不正确
- android - 使用模型类时在firebase中添加数据时设置自定义键
- c - 为什么 math.h 中的 cos 函数比 x86 fcos 指令快
- mysql - 如何优化此内连接查询以减少查询时间