首页 > 解决方案 > 为什么使用 node.js 和 express 发布请求失败

问题描述

我是 Node 的新手,现在只学习了 2 天。我正在学习教程并遇到一些问题。

我们正在使用 、 E 和 制作一个非常简单的天气Node应用程序。尝试搜索城市时,我得到:xpressmodules body-parserhttps

Error: unable to determine the domain name.

我尝试改用该http模块,但得到了相同的消息。该消息同时显示在浏览器和终端中。我用谷歌搜索了这个问题,但找不到任何东西。卡住从这里去哪里。

在此处输入图像描述

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

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.")
})

标签: javascriptnode.jsexpressbackendbody-parser

解决方案


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


推荐阅读