[英]How to fix ' ReferenceError: $ is not defined' while showing result of api in Node Js '
I am trying to get the result from an api and show it in an html page.我正在尝试从 api 获取结果并将其显示在 html 页面中。 I have included body-parser and app.use method.But as soon as i enter value and submit,i am getting the error: ReferenceError: flightStatus is not defined.我已经包含了 body-parser 和 app.use 方法。但是当我输入值并提交时,我收到错误:ReferenceError: flightStatus is not defined。 The api usage is successfull, I am a beginner, so please pardon if it is a fstupid question. api使用成功,我是初学者,如果是一个愚蠢的问题,请原谅。 Any help is greatly appreciated: Here is my server code :非常感谢任何帮助:这是我的服务器代码:
app.post("/iatatracker", function (req, res) {
console.log(req);
let apiKey = 'somekey';
let iataQuery = req.body.iatacode;
let airlineIcaoQuery = req.body.flighticao;
let url = `http://api.aviationstack.com/v1/flights?access_key=${apiKey}&airline_icao=${airlineIcaoQuery}&flight_iata=${iataQuery}`;
http.get(url, function (response) {
response.on('data', function (data) {
let flightData = JSON.parse(data);
let flightStatus = flightData.data.flight_status;
console.log(flightStatus);
});
})
res.write(` The ${flightStatus}`);
}
Here is my html form code这是我的 html 表单代码
<form class="form" name="iata" action="/iatatracker" method="POST" onsubmit="validateForm()">
<label for="iatacode"> Enter IATA Code : (for example : 6E881) </label>
<input type="text" name="iatacode" id="iatacode">
<label for="flighticao"> Enter Flight ICAO Code : (for eg: igo for Indigo Airlines) </label>
<input type="text" name="flighticao" id="flighticao">
<button class="btn" type="submit"> Check Flight History </button>
Thank you so much in advance!!非常感谢您!
So from your code I can get is you are trying to access flightStatus
variable out of its scope.所以从你的代码我可以得到你正在尝试访问其 scope 之外的flightStatus
变量。
You can use res.write(` The ${flightStatus}`);
你可以使用res.write(` The ${flightStatus}`);
inside your response.on
function's callback function as below.在您的response.on
函数的回调 function 中,如下所示。
http.get(url, function (response) {
response.on('data', function (data) {
let flightData = JSON.parse(data);
let flightStatus = flightData.data.flight_status;
console.log(flightStatus);
res.write(` The ${flightStatus}`);
});
});
Solution 2: Taking reference from jfriend00 's comment.解决方案 2:参考jfriend00的评论。
You can create a function to pass the data from response.on
's callback function as below:您可以创建一个 function 来传递来自response.on
的回调 function 的数据,如下所示:
http.get(url, function (response) {
response.on('data', function (data) {
let flightData = JSON.parse(data);
let flightStatus = flightData.data.flight_status;
console.log(flightStatus);
sendResponse(flightStatus);
});
});
function sendResponse(flightStatus) {
res.write(` The ${flightStatus}`);
}
Let me know in comment if this solves your issue.如果这解决了您的问题,请在评论中告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.