简体   繁体   English

为什么使用 node.js 和 express 发布请求失败

[英]Why is post request failing with node.js and express

I'm a complete newbie to Node and only been learning for 2 days now.我是 Node 的完全新手,现在只学习了 2 天。 I'm following along on a tutorial and running into some issues.我正在学习教程并遇到一些问题。

We are making a very simple weather app using Node , E xpress , modules body-parser and https .我们正在使用Node 、 E xpressmodules body-parserhttps modules body-parser制作一个非常简单的天气应用程序。 When attempting to search for the city I get:在尝试搜索城市时,我得到:

Error: unable to determine the domain name . Error: unable to determine the domain name

I tried using the http module instead, but got the same message.我尝试改用http模块,但得到了相同的消息。 The message is displayed both in the browser and terminal.该消息同时显示在浏览器和终端中。 I googled the issue but wasn't able to find anything.我用谷歌搜索了这个问题,但找不到任何东西。 Stuck where to go from here.卡住从这里去哪里。

在此处输入图片说明

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</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 Javascript

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

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

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

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

    https.get(url, function(response) {
        response.on("data", function(data) {
            const weatherData = JSON.parse(data);
            const temp = weatherData.main.temp;
            const description = weatherData.weather[0].description;
            const icon = weatherData.weather[0].icon
            console.log(weatherData);
            console.log(weatherData, temp, description)
            const imageURL = `http://openweathermap.org/img/wn/${icon}@2x.png`
            res.write(`<h1>The temperature in San Luis Obispo is ${temp} with ${description}</h1>`)
            res.write("<img src=" + imageURL +">")
            res.send();
        })
    })
})

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

在您的网址前添加http://https://

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM