最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

处理表单错误

运维笔记admin19浏览0评论

处理表单错误

处理表单错误

我该如何处理来自空表单输入的错误或来自天气API的不可用城市?输入空查询或拼写错误的城市时,服务器将返回错误并停止。

app.get("/", function(req, res) {
  let cityName = req.query.city;
  let url = "";

  if (cityName == null) {
    url = `.5/weather?q=los+angeles&units=imperial&appid=${apiKey}`;
  } else {
    url = `.5/weather?q=${cityName}&units=imperial&appid=${apiKey}`;
  }

  request(url, function(error, response, body) {
    data = JSON.parse(body);

    let weather = {
      city: data.name,
      temp: Math.floor(data.main.temp),
      desc: data.weather[0].description
    };

    var weather_data = { weather: weather };
    res.render("index", weather_data);
  });
});

使用.ejs显示数据

<p><%= weather.city %></p>
<p><%= weather.temp %></p>
<p><%= weather.desc %></p>
回答如下:

要处理空值,您可以在表单上应用表单验证,然后在后端检查var_name === null还是不检查。您还可以检查变量是否为空字符串,也可以使用typeof属性检查其数据类型。

要验证城市,您必须保存一些有天气状况的城市的参考。为了保持应用程序静态,您可以将城市值存储在数组或地图中,并在访问路线时检查城市。如果城市匹配,则执行操作,否则返回抛出错误。如果您需要动态节点应用程序,请使用数据库存储城市并从那里验证城市。

也尝试使用res.send()和res.json()发送json数据而不是渲染。

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论