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();
Related
I know there are plenty of similar questions like my, but I couldn't find any solution for my problem.
I think the issue is that am not getting the product.html and I assume that there is also a problem with the redirection to the product.html.
product.html
<!DOCTYPE html>
<html>
<head>
<title>Product</title>
<meta charset="utf-8" />
</head>
<body>
<form id="product" action="/information" method="POST">
<label for="product_id">Enter product ID: </label>
<input id="product_id" name="product_id" type="text" required />
<input type="submit" />
</form>
</body>
</html>
index.js
const express = require("express");
// load data
const products = require("./data.json");
const app = express();
// static files
app.use(express.static("public"));
// form middleware
app.use(express.urlencoded({ extended: true }));
app.post("/information", (req, res) => {
// ES6 deconstruction syntax, get user input
const { product_id } = req.body;
// search product array
const product = products.find((product) => product.Product_ID === product_id);
if (product) res.json(product);
else res.send("product not found");
});
// redirect all GET requests to product form
app.get("*", (req, res) => {
res.redirect("/product.html");
});
app.listen(8000,console.log(`App listening at http://localhost:8000`));
When I run the code like above, I get the following error: The page isn’t redirecting properly
(Cookies & Cache is deleted). I even tried another project with a node.js server and the localhost in Firefox worked.
When I command the redirection out, I get this error: Cannot GET /
When I use "/" instead of "*" in the redirections, this error appears: Cannot GET /product.html
I don't understand why it doesn't get the product.html and why the redirection doesn't work right.
To render product.html for every endpoint, you can use sendFile rather than redirect, you will need to use path module, which is a core module to resolve the path to html file:
const path = require('path');
//your code
app.get('*', (req, res)=> {
//note that product.html file is in the same directory or you specify
//its relative path
res.sendFile(path.resolve(__dirname, 'product.html'))
})
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()
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
I am trying to write a login page . i got the html page with the login box
im enter email and password than submit to server , on server i got route who get the data check on db if doc exists , if its exists should redirect to main page
the problem is the data i send from form to server always undefined i check here on other ppl questions and i didnt find any good result for this
html login page :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="/css/style.css" />
<title>{{PageTitle}}</title>
</head>
<body>
{{> header}}
<div class="login-box">
<div class="form">
<form action="/get_user" method="post" class="login-form">
<input type="email" name="Email" placeholder="Email"/>
<input type="password" name="Password" placeholder="Password"/>
<button type="submit">login</button>
</form>
</div>
</div>
{{> footer}}
</body>
server code :
const _ = require('lodash');
const express = require('express');
const bodyParser = require('body-parser');
const {mongoose} = require('./db/mongoose');
const hbs = require('hbs');
var {User} = require('./models/user');
var app = express();
app.set('view engine', 'hbs');
const port = process.env.PORT;
hbs.registerPartials(__dirname + '/../views/partials');
app.user(bodyParser.json());
app.use(express.static(__dirname + '/../public'));
app.use(express.static(__dirname + '/../public/images'));
app.use(express.static(__dirname + '/../public/fonts'));
app.listen(port, () => {
console.log(`Started on port ${port}`);
});
app.get('/', (req, res) => {
res.render('login.hbs', {
PageTitle: 'Log In',
ConnectUser: 'Guest'
});
});
app.post('/get_user', (req, res) => {
var body = _.pick(req.body, ['Email , 'Password']);
User.findOne({
Email: body.Email,
Password: body.Password
}).then((user) => {
console.log(body.Email + ' ' + body.Password);
if(!user) {
return res.status(404).send();
}
var fullName = user.First_Name + ' ' + user.Last_Name;
res.redirect('/mainPage', {ConnectUser: fullName});
}).catch((e) => {
res.status(400).send();
});
});
i did few checks and when i call /get_user req.body->var body -> user r empty
the data arnt pass from form to server im also check this route on postman and its work find when i write the body by myself the only problem i can think is the data i send from form arnt send as json and the body parser send only in json format so maybe i need to change the line
app.use(bodyParser.json());
if any 1 can put in the right direction ill appraise that ty.
When using an html form with method post, the data is posted to the server withContent-Type: application/x-www-form-urlencoded instead of JSON.
Json bodyparser will not do anything with that, as its not using JSON format to send the data. See MDN guide under post method.
In your server code, below app.use(bodyParser.json()) add the following:
app.use(bodyParser.urlencoded({extended: true}));
This will add the data onto the request body the way you expect.
Try playing with the form enc-type attribute and see how to configure the bodyparser to get the values you need based on the enc-type.
application/x-www-form-urlencoded
multipart/form-data
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/enctype
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.
}