получение значения json в качестве ключа при выборке - PullRequest
0 голосов
/ 26 мая 2020

Я не уверен, почему это происходит, но я продолжаю получать свое входное значение в качестве ключа внутри моего json объекта, когда я отправляю его через Fetch POST

отправка от клиента

<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>

индекс js маршрут в express

router.post('/authenticate', function(req, res, next) {
  console.log(req.body)

});

что я регистрирую

{ '{"password":"myinputvalue"}': '' }

Я знаю, что это значение уже JSON, поэтому я не могу его проанализировать , кто-нибудь знает, как извлечь значение из ключа. ясно, что я не могу сделать req.body.password ..... есть ли способ сделать req.body.child.value ?? любая информация была бы потрясающей, спасибо.

1 Ответ

0 голосов
/ 26 мая 2020

Используйте Object.keys(req.body), чтобы получить ключ. т.е. '{"password":"myinputvalue"}'.

Затем используйте JSON.parse() для синтаксического анализа ключа до JSON.

Затем просто используйте оператор . для проанализированного объекта JSON, чтобы получить password.


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