将发布请求转换为JSON文件

问题描述 投票:-3回答:1

我有一个关于javascript(post request)的调查表,需要获取用户的答案,然后将其转换为JSON文件,到目前为止,我已经尝试过了,但是我不知道如何进行,我的代码在下面。

exports.answers= (req, res) =>{
    async function getISS(){
        const response = await fetch(req);
        const data =await response.json();
        console.log(data);
    }
    getISS();
    console.log(req.text);
    let resultado =[data];
    res.send(resultado);
};

答案来自这样的调查this is the survey

javascript json post
1个回答
0
投票

有多种方法可以将表单数据发送到服务器。

const form = document.getElementById('my-form'),
  url = 'https://reqres.in/api/users';

form.onsubmit = submit;

function submit(e) {
  e.preventDefault();

  const formData = new FormData(form),
    data = {};

  // Get a JSON object from the form data
  formData.forEach((value, key) => {
    data[key] = value;
  });

  // Using fetch and await/async
  postData(url, data)
    .then(res => {
      console.log('Fetch await/async response is: ' + JSON.stringify(res)); // JSON data parsed by `response.json()` call
    });

  // Using fetch / then
  fetch(url, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
  }).then(
    res => res.json()
  ).then(json => console.log('Fetch / then response is: ' + JSON.stringify(json)));


  // Using XMLHttpRequest
  const req = new XMLHttpRequest();

  req.open('POST', url, true);

  req.setRequestHeader('Content-type', 'application/json');

  req.onreadystatechange = function() {

    if (this.readyState === XMLHttpRequest.DONE && this.status === 201) {

      console.log('XMLHttpRequest response is: ' + req.response);

    }

  }

  req.send(JSON.stringify(data));

}

/*
 * This is the example function on the MDN site for fetch
 * https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
 */
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: '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/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *client
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return await response.json(); // parses JSON response into native JavaScript objects
}
<form action="survey" id="my-form">

  <label for="name">Name</label>
  <input type="text" name="name" id="name">

  <label for="job">Job</label>
  <input type="text" name="job" id="job">

  <button>Submit</button>

</form>

以上任何一种方法都可以将JSON形式的表单数据发送到服务器。我已经使用在线API进行了演示。

© www.soinside.com 2019 - 2024. All rights reserved.