I am new to node js and creating a simple application to query data stored in database(MySql) .So what i am doing is, I have created a database named stock and i am querying it using index.html to show it at get.html but after executing the get request i am not able to get the result.
Here is my app.js
const express=require('express');
const app=express();
const port= 5050;
const bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',(req,res)=>res.sendFile(__dirname + '/index.html'));
app.post('/get',function(req,res){
const mysql=require('mysql');
const con=mysql.createConnection({
host:"localhost",
user:"root",
password:"abc123",
database:"abc",
});
con.connect(function(err){
if(err) throw err;
console.log("Connected");
let sqlQuery='SELECT * FROM stock';
con.query(sqlQuery,(err,rows)=>{
if(err) throw err;
console.log('Data Received:-');
console.log(rows);
});
});
});
app.listen(port);
My Index.html:-
<!DOCTYPE html>
<html>
<head>
<title>My node js app</title>
</head>
<body>
<form action="/get" method="get">
<h1>Welcome to Stock manipulation</h1><br></br>
Select option<select>
<option value=0>Get</option></select>
<input type="submit" id="query" value="get Result">
</body>
</html>
And my get.html
<!DOCTYPE html>
<html>
<head>
<title>Get</title>
</head>
<body>
</body>
</html>
And here is the data stored at database
[ RowDataPacket { id: 1, type: 'BSE' },
RowDataPacket { id: 2, type: 'NSE' } ]
The error i am getting after Submitting the request is
What is your nodejs server saying? In your routes you typically want to return some data. for example in your case your /get route res.send(data). that way your front end can show the data received. Also looks like you need to change your form to be a post not a get (Edit: As Nikos M. mentioned).
If you are new to http requests I recommend downloading Postman to get used to testing your routes requests.
change
<form action="/get" method="get">
to
<form action="/get" method="post">
as you have defined the /get route (app.post('/get',function(req,res){/*..*/}))
to accept only post requests
Also in your /get route handler you should output something. Right now you do not output anything, only log to the node.js console
Related
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?
I wrote a very simple node.js server:
var express = require('express');
var cookieParser = require("cookie-parser");
var app = express();
app.use(cookieParser());
app.get('/', function(req, res){
res.sendFile(__dirname + "/hello.html");
});
app.get('/ajax', function(req, res) {
console.log('ajax request received');
console.log(req.cookies["username"])
})
app.listen(3000);
and a very simple client side html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> Hello World </h1>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
document.cookie = "username=John Doe";
$.ajax({
url: "http://127.0.0.1:3000/ajax",
}).done(function() {
alert('AJAX sent');
});
</script>
</body>
</html>
As you can understand, once the server runs and an end-user sends a get request to localhost:3000, the file 'hello.html' is served to client. The browser saves the cookie "username=John Doe" and sends AJAX request to endpoint localhost:3000/ajax. My intention is to read the content of the cookie in the server (I know that cookies are sent automatically from the client). However, req.cookies["username"] returns undefined.
Do you know why?
The problem is that I send a GET request to localhost:3000 and therefore the cookie is saved in the domain http://localhost. However, when I send an AJAX call to 127.0.0.1, the cookie is not sent because the browser treats 127.0.0.1 and localhost as different domains. Therefore, opening the browser with 127.0.0.1:3000 (instead of localhost:3000) can solve it.
I am very new to reactJs and just started to learn the features of reactJS. I am trying to figure out a way to pass the value from nodeJS to reactJS via server side rendering concept.
In the below example, I was able to define a react component and add it in server and render it in UI but I am not sure how to pass the data to the component that can be used inside the component render function.
client.js
var React=require('react');
var ReactDOM=require('react-dom');
var Component=require('./Component.jsx');
ReactDOM.render(
React.createElement(Component),document
);
Component.jsx
var React=require('react'),
Request=require('superagent')
module.exports = React.createClass({
getInitialState: function () {
return {
};
},
componentWillMount: function () {
},
componentDidMount: function() {
clearInterval(this.intervalID)
},
_handleClick: function () {
alert('You clicked!')
},
render:function(){
return(
<html>
<head>
<title> ReactJS - demo </title>
<link rel='stylesheet' href='/style.css'/>
</head>
<body>
<div>
<h1>react js testing</h1>
<p>This is so cool</p>
<button onClick={this._handleClick}>Click Me!</button>
</div>
<script src='/bundle.js'/>
</body>
</html>
);
}
});
Server.js
require('babel-register')({
presets:['react']
});
var express = require('express');
var app=express();
var React=require('react');
var ReactDOMServer=require('react-dom/server');
var Component=require('./Component.jsx');
app.use(express.static('public'));
app.get('/',function(request,response){
var html=ReactDOMServer.renderToString(
React.createElement(Component)
)
response.send(html)
});
var PORT=4444;
app.listen(PORT,function(){
console.log("Node js listening in port:"+ PORT);
})
Update 1:
I am now able to pass the value to the server side rendered component as below
React.createElement(Component,{object:...})
Now the server side setup works fine.
I need to make this {object:...} available in my client.js also for client side functionality to work. Any idea how to get this value in client.js?
React.createElement
ReactElement createElement(
string/ReactClass type,
[object props],
[children ...]
)
Create and return a new ReactElement of the given type. The type argument can be either an html tag name string (eg. 'div', 'span', etc), or a ReactClass (created via React.createClass).
In the your version in the
React.createElement(Component)
u need use something like
React.createElement(Component, {obj: obj, ...: ...})
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();
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.
}