【问题标题】:getting json value as the key when fetching获取时获取json值作为key
【发布时间】: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


    【解决方案1】:

    使用Object.keys(req.body) 获取密钥。即'{"password":"myinputvalue"}'

    然后使用JSON.parse()将key解析成JSON。

    然后只需在解析的 JSON 对象上使用 . 运算符即可获得 password


    const key = Object.keys(req.body)[0];
    const parsedKey = JSON.parse(key);
    const password = parsedKey.password;
    

    【讨论】:

    • 是的!这对我有用:) 非常感谢!几个小时以来,我一直在处理这个烦人的事情,试图找到解决方案。你碰巧知道为什么我不能完全解析初始对象的值吗?我只是好奇。
    • @monsterpiece,我不明白你在说哪个对象。但是,如果您在谈论 { '{"password":"myinputvalue"}': '' } ,那么您正在尝试解析 JSON 以将其转换为 JSON。那是行不通的。
    猜你喜欢
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多