【问题标题】:Trouble moving data from POST to GET - Node/Express将数据从 POST 移动到 GET 时遇到问题 - Node/Express
【发布时间】:2019-09-17 22:30:11
【问题描述】:

node/express 的新手,正在开发一个天气应用程序,该应用程序从表单中获取位置并发布

<form method="POST" action="/">
  <input id="input" type="text" name="city" placeholder="Search by name or zip code" />
  <button id="button" type="submit"></button>
</form>

我能够在服务器代码中获取数据,但我需要将其传输到我的 app.get 以在我的 API 调用中使用。

app.post("/", function(req, res) {
  let input = req.body.city;
  console.log(input);
});

app.get("/", function(req, res) {
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=imperial&appid=${apiKey}`;

  ..
  code
  ..

  res.render("index", weather_data);
});

【问题讨论】:

  • 从 get 映射中提取逻辑到一个接受 cityName 作为参数的方法中。从 get 和 post 调用该方法。
  • 我不知道为什么快速程序员会忘记它只是 Javascript,并且您可以将通用代码分解为从多个路由调用的函数。但是,这就是你可以在这里做的。

标签: javascript node.js express post get


【解决方案1】:

您需要将表单方法更改为GET(或省略方法属性,GET 是默认方法)。因此,当您提交表单请求时,会转到此路线

app.get("/", function(req, res) {
  const cityName = req.query.city; // see http://expressjs.com/en/5x/api.html#req.query
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=imperial&appid=${apiKey}`;

  ..
  code
  ..

  res.render("index", weather_data);
});

这条路线app.post("/",...)可以删除。

【讨论】:

    【解决方案2】:

    如果我理解正确,您想使用 post 请求将某种数据发送到您的服务器,然后使用 get 请求检索它,对吗? 在这种情况下,您首先需要一个数据库来存储您的数据。 因此,您将数据发送到服务器 -> 将其存储在数据库中 -> 使用 get 请求从数据库中检索数据。

    您可以同时使用 SQL 或 NoSQL 数据库。 我建议你使用带有 mongoose 模块的 MongoDB。

    【讨论】:

      猜你喜欢
      • 2018-11-29
      • 2018-06-19
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多