我已经关注了几篇关于从HTML表单获取数据并将其与API结合使用的文章,但是尽管进行了所有这些研究,但我仍无法将其付诸实践。 This is the SO post that I'm using as a start off point
现在,我只想从HTML表单中获取数据,将其与API调用一起使用,然后console.log
生成结果(只是我知道它正在工作)。
我的Express
设置和HTML
表单都在下面:
快递
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>
为确保API正常运行,我使用了以下代码,并返回了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");
})
答案 0 :(得分:1)
您对API服务器的请求可能有误。将else
块添加到request
中,以查看服务器返回了什么内容。
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);
}
else{
console.log(response.body)
}
此外,例如,以res.send