Error NodeJS : Cannot get - javascript

I'll try to be as clear as I can be. So I'm trying to make a little plateform. I would like that someone connect to the page (in localhost) and then, have the possibility to click on a button, and this button will redirect him to another html page.
So I have a project folder with my "initial" html, my app.js file, and the other html file, which should show itself when clicking on the button.
The server works like this :
var application = require('express')(),
server = require('http').createServer(application),
io = require('socket.io').listen(server),
ent = require('ent'),
fs = require('fs');
application.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
and then, I have the button :
<input type="button" value="blah">
When launching "node app.js" on the terminal, I go on the page, click on the the button and then I got the error "Cannot GET /pfc.html".
Sorry if I'm quite not understandable, I hope someone will understand me.
Thanks and have a nice day!!

You wrote some code to tell your server what to do if the browser asks for /
application.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
Then you wrote a link:
<a href="pfc.html"
which makes the browser ask for /pfx.html.
You haven't written anything in the server side code to tell it how to respond to a request for that. You've only told it how to respond to a request for /.
You could write something similar (application.get('/pfx.html',...) or find some existing middleware for handling static files.

If you have multiple HTML files like pfc.html, you can use
application.use(express.static('public'));
and keep all your html files (including pfc.html) in a folder named public and all those html files that you serve like:
you can look for them at public/pfc.html and such. If the file exists, then the application won't return stuff like Cannot GET /pfc.html and you won't need to write explicit routes for all of them.

Related

making variables completely invisible to user until he does a specific thing

I have 3 main code classes:
1) node.js (running express)
2) the index.html (which loads the moment we enter the site)
3) sck.js which does something (I will explain it after the first and second files)
what I basically do is, I want the user to click on a button. and then the server will output on the page (HTML) or, alert (does not matter to me)
a specific line/word...
I am going literally crazy, I've searched everywhere...
I don't want the user to see the secret word until he clicks the button. not even in the source code (F12) !!!
sck.js is just a jquery that listens to a button click.
app.js:
const express = require('express');
const path = require('path');
const app = express();
//Set a static folder
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, ()=>{
console.log(`starting server port 3000`);
} );
in index.html there is just a button, waiting for the user to click it.
TL;DR : how do I make a variable COMPLETELY invisible for the user, until he clicks a button?
I thought about saving the secret in app.js (because the user cant see whats written there...) and then passing it somehow to the html... but I cant!!!
doesn't it suppose to be easy? it sounds like that .... :(
Thanks!!
A super simple way. Add a route to your express app:
app.get('/getflag', function (req, res) {
res.send('theflag');
});
Add a link to your HTML
Get Flag
Click the link, you will be taken to a page with 'theflag' displayed.

Rendering something on server side by taking input from frontend

I have been asked to perform following task
Take a code input from frontend, i.e user would give his code on frontend (design for a web/landing page)
On backend we have many fields inside an api route
route.get("/", (req, res) => {
const fullName: "Varun Bindal"
const contactNo = 9293939933
const message = "Message I want to display"
//Many more
}
Tell user a way where when we serve his code such that, he could dynamically access/assign the fields we have in the backend into his code
I did some googling and found the express officially recommends ejs for server side compilation of webpage
Can someone please help me figure out how we can achieve this?
Yes you can!
Firstly you must include ejs in your project, configure it in your server.js file for example, then you can call res.render() in your callback parameter on route.get().
In your html or javascript you can create a placeholder which gets populated.
Example (server):
route.engine('html', ejs.renderFile);
route.engine('js', ejs.renderFile);
route.get('/', (req, res) => res.render(path.resolve(__dirname, '
../ui/index.html'), {
'myVal': 42,
}));
Example (client html, js, etc...):
<%= myVal %>

Socket.io: io is not defined

So, I am trying to get data on my node.js file instead of directly getting it on my JS file.
I a using Socket.io 2 here, Below is a snapshot of my code and this is also the first time I am using Websocket with Node.
I am doing something like
var socket = require('socket.io')
//Home Page
app.get("/", function(req, res) {
var cryto = io.connect("https://xyfz.com/);
cryto.on('trades', function (tradeMsg) {
console.log(tradeMsg);
});
res.render("index");
});
I also tried something like
var io = socket("https://abc.io/");
and
var socket = require('socket.io')
var io = socket();
which was throwing errors like server.listeners is not a function and io.connect is not a function.
I am certain that I messing up stuff here so can someone guide me about the correct way of doing it?
Two things which are wrong .
First Consider using Socket.io-client instead of Socket.io.
Second and very much important.
Never ever make API calls inside your routes. This will trigger a API call everytime user opens your website or webpage
You can also expect an error "Unexpected headers" or something like that.
Always, Try do declare it outside any routes in your NodeAPP.
Same goes for socket.io as well

Run a server side Javascript version with Express

recently i got into web programming and i started to learn javascript,node.js and express.js and my goal is to run a server side javascript function(to be more accurate a function to search something in a mysql db) when a button got pressed on a html.
My dir structure is like this : A main dir, containing a dir "page". Page containing server.js, dbFunctions.js and "public" dir. Public containing a index.html,style.css and some images.
Server.js :
var express = require('express');
var app = express();
var path = require('path');
var port = 8888;
//allow to use static files
app.use(express.static("public"));
//start server
app.listen(port);
console.log("Server running on port" + port);
HTML Example
<html>
<head>
<title>Test html</title>
</head>
<label for="key">Valid key:
<input id="key" name="key" required>
</label>
<input type="checkbox" name="test" value="testval" checked>
<button type="button">Button</button>
</html>
So basically the HTML got a input field,a checkbox and a button, and if the button is clicked it should run a function from dbFunctions.js with parameter(taken from the field and the checkbox as bool) on server side
I heard something about ajax calls etc but those explanations are usually very confusing. Is there any "hello world" example?
Greetings.
Sounds like you're quite new to JS so I would recommend breaking this down into two components.
One is your server side code and the other is your front end code. As you mentioned you find the front end code confusing, I would suggest coming back to that, once you have got your server side code working.
To make things easy, you could use something like express generator which boiler plates everything for you.
You can then follow this guide which will show you how you can set up a route which you will be able to make some sort of request to. Like a POST, GET or PUT request (which is what your front end AJAX code will eventually make a call to).
My advice would be to try get your route working and testing it with something like Postman so you don't have to worry about building the front end simultaneously.
When you are happy with the back end, you can start look into how to make requests from the browser to hit your new back end route you have set up.
Yes, check out this amazing post
https://medium.com/#adnanrahic/hello-world-app-with-node-js-and-express-c1eb7cfa8a30
This is an example hello world node js application with express js.
First you need to make your html page call your server. To do that you can :
Place your button inside a form and set your form action equal to /getHelloWorld
Create a javascript script and call your /getHelloWorld in ajax
In your server you need to catch route like this :
Server.js :
var express = require('express');
var app = express();
var path = require('path');
var port = 8888;
//allow to use static files
app.use(express.static("public"));
app.get('/getHelloWorld', (req, res) => {
res.send('hello world !');
});
//start server
app.listen(port);
console.log("Server running on port" + port);
with this your server will return Hello World When you'r calling this road : /getHelloWorld.
Then you just need to replace code inside route catch by a code to call your DB and return your DB response.

How to get the params in a Express route when I am using app.use() for the home page in my server

So, basically I have this middleware on my server.js file: app.use(express.static(__dirname + '/public')) for the home page.
It's possible to show the same home page when a user hit this route: app.get('/ref=:refId') and still show localhost:3000/ref=Asldoe2231sSLexe2 in the address bar?
Now I know that I can achieve this behavior using query string like so: localhost:3000/?ref=Asldoe2231sSLexe2 and then get the query string using req.query.ref on the server, the problem is I cannot use app.use(express.static(__dirname + '/public')) directly if I have this route app.get('/', (req, res) => {.... How can I solve this?
My goal is either grab the refId value on the client, send it to the server and check if exists in the database or check it directly as soon as the client hit the route, I rather prefer the second option which is a cleaner way of doing it.
What you want to do don't have a relationship with
app.use(express.static(__dirname + '/public')). It is used for giving the path to static files such as CSS, images in your application.
You can get refId by req.query.ref and pass it to the page you are rendering.
One way is :
res.locals.refId = req.query.ref and in your view use refid
Second way is :
res.render('<file_you_are_rendering>',{refId:req.query.ref})

Categories