Nothing to geocode - Weather API - Nodejs - node.js

I am new to Nodejs and trying to use weather api.
When I test the link in browser, it gives me accurate answer
http://api.openweathermap.org/data/2.5/weather?q=karachi&appid=dcf486a78f2b8e898c4b1a464a1b31e1
while it keeps throwing error.
const express = require("express")
var logger = require("morgan")
var path = require("path")
var bodyParser = require("body-parser")
let requested = require('request');
var app=express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.set("views", path.resolve(__dirname,"views"))
app.set("view engine",'ejs')
app.use(logger("short"))
app.get("/",function(request,response)
{
response.render("homepage")
})
app.post('/', function(request, response) {
var urlOpenWeatherCurrent = 'http://api.openweathermap.org/data/2.5/weather?'
var queryObject = {
APPID: "dcf486a78f2b8e898c4b1a464a1b31e1",
city: request.body.cityName
}
console.log(queryObject)
requested({
url:urlOpenWeatherCurrent,
q: queryObject // In many tutorials they used 'qs' instead of 'q'. I don't know why.
}, function (err, response, body) {
// response.send('You sent the name ' + request.body.cityName + ".");
if(err){
console.log('error:', error);
} else {
console.log('body:', JSON.parse(body));
}
});
});
app.use(function(request,response)
{
response.status(404)
response.send("Error")
})
app.listen(3000,()=>console.log("Working"))
Error
{ APPID: 'dcf486a78f2b8e898c4b1a464a1b31e1', city: 'karachi' }
'Invalid API key. Please see http://openweathermap.org/faq#error401 for more info.'
If I change q to qs in nodejs, then
{ APPID: 'dcf486a78f2b8e898c4b1a464a1b31e1', city: 'karachi' }
body: { cod: '400', message: 'Nothing to geocode' }
Note that changing q to qs in raw html API link also gives
{"cod":"400","message":"Nothing to geocode"}
I believe from the response that I should use qs in nodejs, because at least this time it is not considering API key wrong. But in the API link, we have q and not qs. So how come qs makes sense? Besides, as far as I Understood, it is not properly concatenating the API strings together, resulting in the malfunctioning. But I don't know how to print the entire link in console to validate what I just said.
views/homepage.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form class="pure-form" action="/" method="POST">
<input type="name" placeholder="City name" name="cityName" autofocus required>
<input type="submit" valuue="Go">
</form>
</body>
</html>

embed the "q" and "api key" with open weather url like "http://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${apiKey}"
also Check this link
https://codeburst.io/build-a-weather-website-in-30-minutes-with-node-js-express-openweather-a317f904897b

Related

Error 405 when opening project having Open Weather API via Github pages [duplicate]

This question already has answers here:
How to publish a website made by Node.js to Github Pages?
(8 answers)
Closed 11 months ago.
My app.js
const express = require ("express");
const res = require("express/lib/response");
const https = require ("https");
const bodyParser = require ("body-parser");
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.get("/",function(request, response){
response.sendFile(__dirname+"/index.html");
})
app.post("/", function(req, res){
console.log(req.body.cityName);
// console.log("POST request received.");
const query=req.body.cityName;
const apiKey="796ea31271937af05a23079696c29758";
const units = "metric";
const url = "https://api.openweathermap.org/data/2.5/weather?q="+query+"&appid="+apiKey+"&units="+units;
https.get(url, function(response){
console.log(res.statusCode);
response.on("data", function(data){
//console.log(data);
const weatherData= JSON.parse(data);
// console.log(weatherData);
// const object = {
// name: "Ann",
// favouriteFood: "Butter Chicken"
// }
// console.log(JSON.stringify(object));
const temp = weatherData.main.temp;
console.log("Temperature : "+temp);
const feelsLike = weatherData.main.feels_like;
console.log("Feels like : "+feelsLike);
const weatherDescription = weatherData.weather[0].description;
console.log("Weather Description : "+weatherDescription);
const icon= weatherData.weather[0].icon;
imageURL = "http://openweathermap.org/img/wn/"+icon+"#2x.png"
// Method 1
//response.send("<h2>The temperature in Montreal, Quebec is "+temp+" degrees Celcius.</h2><br><h2>The weather is currently "+weatherDescription+"</h2><br><h2>The feels like temperature is "+feelsLike+" degrees Celcius. </h2>")
// Method 2
res.set("Content-Type", "text/html");
res.write("<h2>The temperature in "+query+" is "+temp+" degrees Celcius.</h2>")
res.write("<p>The weather is currently "+weatherDescription+"</p>")
res.write("<h4>The feels like temperature is "+feelsLike+" degrees Celcius. </h4>")
res.write("<img src="+imageURL+">");
res.send();
});
});
})
app.listen(3000, function(){
console.log("Server is running on port 3000.");
})
My index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Weather Project</title>
</head>
<body>
<form action="/" method="post">
<label for="city-input">City Name: </label>
<input id="city-input" type="text" name="cityName" />
<button type="submit">Go</button>
</form>
</body>
</html>
When I test this app.js on my local server it shows the expected response, i.e. the temperature of the city that I send in POST request. But when I run the project using my Github pages link it shows the index.html but when I send the city as POST request,I get a 405 error on the next page. I am new so I am not sure what is wrong but my initial thought was that it is something related to the API key? as in the key ID?
Please help.
It seems like github repo doesn't support the post requests. Did you try using the different hosting platform like firebase?

POST request not working in NodeJs app in Cpanel

I was creating a Node App using Express JS. There's a route which accepts a POST Request. The app works fine on localhost, but when I host on Cpanel Shared Hosting, I get the following error for POST request. GET works fine. Can anyone please help or guide where I went wrong?
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /v1/email</pre>
</body>
</html>
My Express JS code
var app = express();
var em =require('./mailjet')
var bodyParser = require('body-parser');
app.use(bodyParser.json())
app.get('/v1', function (req, res) {
return res.json('Hello World');
})
app.post('/v1/email', function (req, res) {
let {name, email, message}=req.body
if (!name || !email || !message){
return res.status(400).send({
'Message':'Bad Request'
})
}
em.request(name, email, message)
return res.status(200).send({
'Message':'Email Sent'
});
})
app.listen()

How to resolve "Unresolved variable or type data" warnings when using EJS?

I'm using EJS as Template engine. Everything looks like working fine, but I have these weak "Unresolved variable or type data" warnings in IntelliJ. How to get rid of these warnings? Is anything wrong with the code?
app.js:
var express = require('express');
var app = express();
var hostname = 'localhost';
var port = 3000;
app.set('view engine', 'ejs');
app.use('/static', express.static('static'));
app.get('/', (req, res) => {
res.sendFile(`${__dirname}/index.html`);
});
app.get('/profile/:id', (req, res) => {
var userData = {
id: req.params.id,
firstName: 'John',
lastName: 'Peterson',
age: 23,
active: true,
interests: ['Design', 'Web', 'Acting']
};
res.render('profile', { data: userData });
});
app.get('*', (req, res) => {
res.sendFile(`${__dirname}/404.html`);
});
app.listen(port);
console.log(`Server running at http://${hostname}:${port}`);
views/profile.ejs:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My Profile</title>
<link rel="stylesheet" href="../static/style.css">
</head>
<body>
<h2>My Profile Template</h2>
<p>ID: <%=data.id%></p>
<p>Name: <%=data.firstName%> <%=data.lastName%></p>
<p>Age: <%=data.age%> years</p>
<p>Active: <%=data.active%></p>
</body>
</html>
I solved this problem, by adding spaces between %=%.
<p>Name: <%= data.firstName %> <%= data.lastName %></p>
It looks like you need to export the data object somewhere in your code.
Try to add module.exports = { data: {}; } to the end of your app.js file.
To make autocomplete work correctly, you should either export a real object (userData) instead of an empty one, or use TypeScript.

ReferenceError: app is not definied in Node.js - SteamWebAPI

Eh, my third question about API and still cannot manage to work it the way I want... Anyways, I have two files: app.js and index.html.
My index.html is simple form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Steam</title>
</head>
<body>
<form>
Steam User ID: <br>
<input type="text" name="steamid"><br>
<input type="submit" value="PoĊĦalji">
</form>
</body>
</html>
Form is getting Steam User ID and submit button, to submit this form.
My app.js:
//Express
var express = require('express');
var server = express();
//SteamWebAPI
var SteamWebAPI = require('steamwebapi').SteamWebAPI;
SteamWebAPI.setAPIKey('7DB297EBF0D0FC352539B4AF9C7C850B');
//Render - Form
server.get('/user_id', function(req, res) {
app.render('form', function(err, html) {
if(err)
return res.send(err);
else
return res.send(html)
});
});
//Route - Form
server.post('/user_info', function(req, res) {
var _userID = req.body.userId;
//Variable - SteamWebAPI
SteamWebAPI.getRecentlyPlayedGames(_userID, 5, function(req, res) {
return res.json(response.response.games);
});
});
// Localhost
server.listen(3000, function() {
console.log('Server: 3000');
});
Someone correct me if I'm wrong:
-after i require express and steamwebapi, i'm getting informations (in this case steam id) from form,
- then this variable _userID is equal to req.body.userId; and i dont know why...anyways...error im getting is: **ReferenceError: app is not defined
**
Can someone help me with this? Is this Node too hard? Like, It's simple. User enter id in form, server getting form? and returning in json format? What I'm doing wrong???
PS: Doing simple way, when I enter Steam ID, I get in console.log game: CS:GO for example...Is there way to display as icon? Obviously I cannot in console so I need to use angular, ember, or what? Thx folks
Just add this before using app variable:
var app = express();

How to capture streaming results with Prototype Ajax.request

High Level Overview:
I have a nodejs expressjs server that makes use of the PostgreSQL nodejs driver called pg. I have a html file served to the client browser that when you click a button invokes a expressjs route on my expressjs server. This route will select data out of a PostgreSQL database and return it to the client html file. The problem is the route emits a response for every row selected in the query to the database. All the client (html browser) gets is the first row. I can write to the nodejs console server side and get all the rows to be displayed, but obviously that does me know good on my webpage.
Question:
How do I get my client html file to write to console on the client for every row emitted out of my expressjs route /pg? My assumption was on the client that the onSuccess would be fired for every row emitted out of my expressJS route.
NodeJS\ExpressJS Server File:
var express = require('express');
var pg = require('pg');
var app = express();
var MemoryStore = express.session.MemoryStore;
var conString = "postgres://joe_user:password#localhost/dev_db";
var client = new pg.Client(conString);
client.connect();
app.get('/home', function(req,res){
res.sendfile(__dirname + '/views/index.html');
});
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use
(
express.session
(
{
key: 'some-key',
secret: 'some-We1rD sEEEEEcret!',
cookie: { secure: true },
store: new MemoryStore({ reapInterval: 60000 * 10 })
}
)
);
app.use
(
function(err, req, res, next)
{
// logic
console.error(err.stack);
res.send(500, 'Something broke!');
}
);
app.get('/pg', function(req, res)
{
var query = client.query("SELECT * FROM junk_data;"); //Returns 7000 rows with 8 columns total
query.on('row', function(row)
{
res.send(row);
console.log(row);
}
);
}
);
process.on('uncaughtException', function (err) {
console.log(err);
});
app.listen(4000);
HTML File:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo: dojo/request/xhr</title>
<!--<link rel="stylesheet" href="style.css" media="screen">-->
<!--<link rel="stylesheet" href="../../../resources/style/demo.css" media="screen">-->
</head>
<body>
<h1>Demo: dojo/request/xhr</h1>
<p>Click the button below to see dojo/request/xhr in action.</p>
<div>
<button id="textButton2" onclick="SubmitPGRequest();">Call Express Route For PostgreSQL</button>
<!--<input type="button" value="Submit" onclick="SubmitRequest();"/> -->
</div>
<br /><br />
<div id="resultDiv">
</div>
<!-- load dojo and provide config via data attribute -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.7/prototype.js"></script>
<script>
function SubmitPGRequest()
{
new Ajax.Request( '/pg', {
method: 'get',
onSuccess: function(response){
<!--alert(response.responseText); -->
if(response.done) {
alert('Done!');
}else {
console.log(response.responseText);}
},
onFailure: function(){
alert('ERROR');
}
});
}
</script>
<
/body>
Ok so I figured out an answer to my question.
With the nodejs pg driver you can just send all the rows in the result object once the query has completed(end) and send them in one go. Below is what I ended up having in my expressjs server route to send all rows back the client.
//fired once the function above has completed firing.
query.on('end',(result)
{
res.send(result.rows);//send all rows back to client.
}

Resources