【问题标题】:How do I access data from a fetch in a get method?如何从 get 方法中的 fetch 访问数据?
【发布时间】:2017-10-30 14:46:09
【问题描述】:

好的,所以我觉得这比它需要的要微不足道,但由于某种原因,当它传递给 get 方法时,我无法从我的“身体”中获取信息。我尝试了许多不同的方法来访问它,但没有任何方法可以解决问题。指导非常感谢。以下是我的代码:

 ---------------fetch method----------------
  var x = e.target.phone.value;
  var y = e.target.email.value;

  console.log(x); // proper output
  console.log(y); // proper output

  fetch('/api/insert', 
  {
    accept: 'application/json',
    body: {
      phone2: x,
      email2: y
    }
  });
 ------------get method--------------
app.get('/api/insert', (req, res) => {
    const phone = req.body.phone2; <-- Am I accessing the data incorrectly?

    const email = req.body.email2; <-- Am I accessing the data incorrectly?
    console.log(phone); // getting undefined here... Why?
    console.log(email); // and here...
    });
    });

【问题讨论】:

  • console.log(req)console.log(res) 的输出是什么?

标签: javascript node.js reactjs express


【解决方案1】:

您需要使用req.query.phone2req.query.email2

GET 请求的参数作为 URL 上的查询参数发送(GET 请求不发送正文),Express 将查询参数放入 req.query

【讨论】:

    【解决方案2】:

    我认为你应该这样称呼它:

    fetch('......')
          .then((response) => response.json())
          .then((responseJson) => {
            return responseJson.movies;
    })
    .catch((error) => {
          console.error(error);
    });
    

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多