I've following several articles about taking data from a HTML form and using it with an API, but despite all of this research, I'm unable to put it into practice. This is the SO post that I'm using as a start off point
For now, I simply want to take data from a HTML form, use it with an API call and console.log
it results (just so I know that it's working).
My Express
set up and HTML
form are both below:
Express
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var request = require("request");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));
const apiUrl = "https://api.darksky.net/forecast/";
const apiKey = "XXX";
app.get("/", function(req, res){
res.render("index");
});
app.post('/results', function(req, res){
var lat = req.body.latitude;
var long = req.body.longitude;
request(apiUrl + apiKey + "/" + long + "," + lat, function(error, response, body){
if (!error && response.statusCode == 200) {
var parsedData = JSON.parse(body);
console.log(parsedData.currently.summary + " " + parsedData.currently.temperature);
}
});
});
app.listen(3000, function(){
console.log("Server has started");
})
HTML
<form action = "/results" method ="POST">
<ul>
<li>
<label for = "latitude">Latitude</label>
<input type="text" name="latitude" placeholder="e.g. 19.4326">
</li>
<li>
<label for = "longitude">Longitude</label>
<input type="text" name="longitude" placeholder="e.g. 99.1332">
</li>
</ul>
<button type="submit">Get the weather</button>
</form>
To make sure the API is working, I used the code below and it returns clear 68.16
:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var request = require("request");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));
const apiUrl = "https://api.darksky.net/forecast/";
const apiKey = "XXX";
var lat = 23;
var long = 23;
app.get("/", function(req, res){
res.render("index");
});
request(apiUrl + apiKey + "/" + long + "," + lat, function(error, response, body){
if (!error && response.statusCode == 200) {
var parsedData = JSON.parse(body);
console.log(parsedData.currently.summary + " " + parsedData.currently.temperature);
}
});
app.listen(3000, function(){
console.log("Server has started");
})