【发布时间】:2020-09-13 10:12:39
【问题描述】:
我不确定为什么会发生这种情况,但是当我通过 fetch POST 发送它时,我不断将输入值作为我的 json 对象内部的键
从客户端发送
<script type="text/javascript">
$(function(){
//show the modal when dom is ready
$('#loginModal').modal('show');
});
async function postData(url = '',data) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default , no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
document.getElementById("loginButton").addEventListener('click',function(){
console.log('sending data',document.getElementById("passholder").value)
postData(`http://${window.location.hostname}:3000/authenticate`, {password: document.getElementById("passholder").value} )
.then(() => {console.log('returned from server') });
})
</script>
在 express 中索引 js 路由
router.post('/authenticate', function(req, res, next) {
console.log(req.body)
});
我记录的内容
{ '{"password":"myinputvalue"}': '' }
我知道这个值已经是 JSON,所以我无法解析它,有谁知道如何从键中提取值。显然我不能做 req.body.password .....有什么办法可以做 req.body.child.value 吗?任何信息都会很棒,谢谢。
【问题讨论】:
标签: node.js json express post fetch