简体   繁体   English

如何修复类型错误无法读取天气预报项目中未定义的属性“cityName”?

[英]How to fix Type Error cannot read property 'cityName' of undefined in the weather forecast project?

I had seen every syntax but I could see any type of error in my project.我看过每一种语法,但我可以在我的项目中看到任何类型的错误。 Can you help me where is the problem really is?你能帮我看看问题出在哪里吗?

I wanted to make a weather project by the api but when I load the code in the browser it is showing the type error "cityName" but I don't see any error in there.can you help me out where is the problem is I give a pic also.我想通过 api 制作一个天气项目,但是当我在浏览器中加载代码时,它显示类型错误“cityName”,但我没有看到任何错误。你能帮我解决问题出在哪里吗?也给一张照片。

HTML file HTML 文件

 <html lang="en" dir="ltr">
        <head>
            <meta charset="utf-8">
            <title>Weather Forcast</title>
        </head>
        <body>
            <form action="/" method="post">
                <label for="cityInput">City Name:</label>
                <input id="cityInput" type="text" name="cityName">
                <button type="submit">Go</button>
            </form>        
    
        </body>
    </html>

JavaScript file JavaScript 文件

    const express= require("express");
    const https = require("https");
    const app = express();
    
    app.get("/", function(req, res){
        res.sendFile(__dirname + "/index.html");
    
    });
    
    app.post("/", function(req, res){ 
        const query =req.body.cityName;
        const apiKey ="e3e24d2fb12aafc8d8bf05b91d5f0ae0";
        const unit ="metric";
        const url ="https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apiKey + "&units=" + unit;
    
        https.get(url, function(response){
            console.log(response.statusCode);
    
            response.on("data", function(data){
                const weatherData = JSON.parse(data)
                const temp = weatherData.main.temp
                const weatherDescription = weatherData.weather[0].description
                res.write("<p>The weather is currently" + weatherDescription + "</p>");
                res.write("<h1>The tempreature in "+ query +" is " + temp +"degress Celcius.</h1>")
                res.send();
                
            })
       })
    });
    
    
    
    
       app.listen(3000, function(){
           console.log("Server is running on Port 3000");
       })

The error I got from the browser我从浏览器得到的错误

Look like you haven't use bodyParser yet, so req.body will be undefined.看起来你还没有使用 bodyParser,所以 req.body 将是未定义的。

Try add bodyParser to your JavaScript file to see if it work尝试将 bodyParser 添加到您的 JavaScript 文件中,看看它是否有效

const express= require("express");
const https = require("https");
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json()); 

you have not installed body-parser which parse the incoming request and you are using req.body.cityName which javascript would not understand.您尚未安装解析传入请求的body-parser ,并且您正在使用req.body.cityName无法理解的 req.body.cityName。

So, refer this link body-parser and refer to the following code.因此,请参考此链接body-parser并参考以下代码。

//jsonhint express versio:6.0
  const express= require("express");
  const https = require("https");
  const bodyParser = require("body-parser");
  const app = express();
  

  app.use(bodyParser.urlencoded({
  extended: false
  }));

  app.get("/", function(req, res){
      res.sendFile(__dirname + "/index.html");
  
  });
  
  app.post("/", function(req, res){ 
      const query =req.body.cityName;
      const apiKey ="e3e24d2fb12aafc8d8bf05b91d5f0ae0";
      const unit ="metric";
      const url ="https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apiKey + "&units=" + unit;
  
      https.get(url, function(response){
          console.log(response.statusCode);
  
          response.on("data", function(data){
              const weatherData = JSON.parse(data)
              const temp = weatherData.main.temp
              const weatherDescription = weatherData.weather[0].description
              res.write("<p>The weather is currently" + weatherDescription + "</p>");
              res.write("<h1>The tempreature in "+ query +" is " + temp +"degress Celcius.</h1>")
              res.send();
              
          })
     })
  });
  
  
  
  
     app.listen(3000, function(){
         console.log("Server is running on Port 3000");
     })

You have to parse the request body before performing any kind of operation.在执行任何类型的操作之前,您必须解析request正文。 You can use express.json() middleware function to parse the request body.您可以使用express.json()中间件 function 来解析请求正文。

For more information visit Express Official Documentaion欲了解更多信息,请访问Express 官方文档

app.use(express.json());

Final code:最终代码:

const express= require("express");
const https = require("https");
const app = express();

// Middleware function to parse the request body;
app.use(express.json());

app.get("/", function(req, res){
    res.sendFile(__dirname + "/index.html");

});

app.post("/", function(req, res){ 
    const query =req.body.cityName;
    const apiKey ="e3e24d2fb12aafc8d8bf05b91d5f0ae0";
    const unit ="metric";
    const url ="https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apiKey + "&units=" + unit;

    https.get(url, function(response){
        console.log(response.statusCode);

        response.on("data", function(data){
            const weatherData = JSON.parse(data)
            const temp = weatherData.main.temp
            const weatherDescription = weatherData.weather[0].description
            res.write("<p>The weather is currently" + weatherDescription + "</p>");
            res.write("<h1>The tempreature in "+ query +" is " + temp +"degress Celcius.</h1>")
            res.send();
            
        })
   })
});




   app.listen(3000, function(){
       console.log("Server is running on Port 3000");
   })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复 React 项目中的“TypeError:无法读取未定义的属性‘继承’”? - How to fix “TypeError: Cannot read property 'inherits' of undefined” in React project? 如何:修复 ReactJS 类型错误 - 无法读取未定义的属性“地图” - How to: Fix ReactJS Type Errror - Cannot read property 'map' of undefined 如何修复错误“错误类型错误:无法读取未定义的属性‘0’” - how to fix the error "ERROR TypeError: Cannot read property '0' of undefined" 如何修复错误无法读取未定义的属性“trim” - How to fix error Cannot read property 'trim` of undefined 如何修复错误类型错误:无法读取未定义的属性“地图” - How to fix the error TypeError: Cannot read property 'map' of undefined 如何修复“未捕获的类型错误:无法读取未定义的属性‘替换’”错误? - How to fix "Uncaught TypeError: Cannot read property 'replace' of undefined" error? 如何解决错误“无法读取未定义的属性&#39;setState&#39;” - How to fix the error `Cannot read property 'setState' of undefined` 如何修复无法读取未定义错误的属性“currentTarget” - How to fix Cannot read property 'currentTarget' of undefined error 如何修复“TypeError:无法读取未定义的属性 'id'”错误? - How to fix “TypeError: Cannot read property 'id' of undefined” error? 如何修复节点中的“无法读取未定义的属性&#39;trim&#39;”错误 - How to fix “Cannot read property 'trim' of undefined” error in node
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM