gpt4 book ai didi

javascript - 从表单呈现数据并通过 API 使用它

转载 作者:行者123 更新时间:2023-12-01 01:16:23 25 4
gpt4 key购买 nike

我关注了几篇有关从 HTML 表单获取数据并将其与 API 一起使用的文章,但尽管进行了所有这些研究,我仍无法将其付诸实践。 This is the SO post that I'm using as a start off point

目前,我只想从 HTML 表单中获取数据,将其与 API 调用一起使用,并生成结果(只是为了让我知道它正在工作)。

我的 Express 设置和 HTML 表单如下:

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>

为了确保 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");
})

最佳答案

您对 API 服务器的请求可能有错误。将 else block 添加到 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

关于javascript - 从表单呈现数据并通过 API 使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54733333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com