Search code examples
javascriptnode.jsexpressbackendbody-parser

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. I'm following along on a tutorial and running into some issues.

We are making a very simple weather app using Node, Express, modules body-parser and https. When attempting to search for the city I get:

Error: unable to determine the domain name.

I tried using the http module instead, but got the same message. 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.

enter image description 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

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

Solution

  • Add http:// or https:// in front of your url