I don't fully understand what app.get('/consult') - javascript

I am new to express and I still struggle with the meaning of app.get().
In my HTML page, I have a button with the id=consult-button.
I gave it the following script:
document.getElementById("consult-button").addEventListener("click", function() {
window.location.href = '/consulting';
});
On my app.js file, on the other hand, I have:
app.get('/consulting', (req, res) => {
const client = new pg.Client(config);
client.connect();
client.query('SELECT * FROM questionaire', (err, result) => {
if (err) {
console.log(err);
}
res.send(result.rows);
client.end();
});
});
Can someone help me understand this? Tell me if what I am writing is right:
when the button is clicked, a url with the name "consulting" is created. then app.get call on that url and sends the results of the query in that url?

When the user clicks on the button on the web page, the browser is going to send an HTTP GET request to the endpoint on the server (/consulting),
for example, if your website domain is www.example.com, the browser is going to send the request to www.example.com/consulting,
or if your domain is 192.168.1.50:3000 for example in case you're working on localhost for example, the website is going to send a request to 192.168.1.50:3000/consulting.
But this piece of code doesn't only send a request to the server, it also changes the URL to /consulting, (ex: www.example.com becomes www.example.com/consulting).
Now when the request travels from the website (the computer of the website visitor) to the back-end server (which is express in your case), express is going to catch this request in the following controller (it's called a controller)
app.get('/consulting', (req, res) => {
const client = new pg.Client(config);
client.connect();
client.query('SELECT * FROM questionaire', (err, result) => {
if (err) {
console.log(err);
}
res.send(result.rows);
client.end();
});
});
app.get is the controller which catches this request and handles it because it's
app.get('/consulting') which matches the destination of the request.
Now this controller has a bunch of codes, it basically sends a request to the Postgres database saying "SELECT * FROM questionaire" which basically means give me all the entries inside the questionaire table.
the database responds with that, so the server (the controller) takes care of the response from the database and forwards it back to the website.
Hope this helps.

Related

Why is "module.exports = (req, res) => {" stopping my routing from working

A href is called like so:
<a class="navlink" href="/auth/logout">Logout</a>
When clicked a controller in the middleware(named "auth.js"), and another controller "logout.js" is called , it doesn't do anything. The session should destroy and redirect the index. Instead the pay flinches slightly but stays on the current page.
"auth.js"
const User = require('../database/models/User')
module.exports = (req, res, next) => {
User.findById(req.session.userId, (error, user) => {
if (error || !user) {
return res.redirect('create')
}
next()
})
}
logout.js"
module.exports = (req, res) => {
req.session.destroy(() => {
res.redirect('/')
})
}
I expect the controller to direct to the index.
If the button is ultimately triggering an ajax call through the controller to your server, then ajax calls don't by themselves pay any attention to redirect responses (so thus the res.redirect() does nothing). You would have to have code in the client-side controller that sees that redirect response from the ajax call and then acts on it by setting window.location accordingly to cause the browser page to change.
Things in the browser that do automatically follow a redirect in the response:
Type a URL in the URL bar of the browser
Following a link in a web page (such as Click here)
Setting window.location via Javascript
The response from a form post (submitted automatically by the browser, not via Javascript)
So, if your request is being sent via Javascript, then it won't automatically follow a redirect response. Your Javascript would have to see the response come back, see that it's a 3xx response, fetch the redirect location from the response and then set window.location to tell the browser to go to that new location.

Nodejs cannot Read and Write simultaneously

I am currently trying to develop a NodeJS application, which contains 3 main Routes:
app.get('/1',(req, res) => {
res.sendFile(path.join(__dirname, './index.html'))
});
app.post('/1',(req, res) => {
model.sharetime(req.body.zeit);
});
and
app.get('/receive', (req, res) => {
res.json(model.receivetime());
});
The post Route /1 will be called once ever second, which receives a value that is put into an array.
The problem that I encounter is, each time I want to call the route /receive while the /1 get route is open, there is no response whatsoever,
after I restart the server, suddenly I get the response that I requested.
Which basically means, I cant have the route /1 which opens my index file open which I need for the application to post results back to the server and simultaneously receive the updated values via the route /receive.
Please help :)
You're not responding to the request, you're merely calling a function with a value from the posted form. Add at least a res.end(); to that route handler.

Redirect after already used response Node js

I want to render some page and after certain amount of seconds it needs to be redirected to another page. However, I get an "Can't set headers after they are sent." From what I read, the response should be used only once, though I'm not sure if this is true. I would appreciate any help or solution to this particular problem.
app.get('/', function (req, res) {
var message = req.flash();
res.render('index', { message: req.flash('message'), hassError: message.length > 0} );
});
app.get('/error', function (req, res) {
var timeout = 3000;
setTimeout(function (err) {
console.log('finished');
if (err)
throw err;
console.log('################');
res.redirect('/');
}, timeout);
res.render('partials/404');
});
"finished" gets printed and then it throws error, but not the err specified in callback.
You can't use this approach - rendering means sent to browser with headers, then the HTTP request is closed by browser. You can't send a second response.
You'll have to do the timeout logic in JavaScript on the page, not server:
<script>
var timeout = 3000;
setTimeout(function () {
window.location = "http://www.yoururl.com";
}, timeout);
</script>
You can't send multiple responses to a single request. It's like if someone asks you for a burger, you give them a burger, and they walk away. Some time later you lob another burger at the back of their head. They aren't going to catch it.
In this case, you'll need to handle redirecting on the client-side. If this is just a regular page render, you can use the refresh attribute of a meta tag.
<meta http-equiv="refresh" content="2; url=http://path/to/my/page/" />
If this is an AJAX request, you'll need to have the client perform the redirect after a delay.
The redirect you are trying to send should be done either on the server side right when the user hits the server, or done on the browser after the 404 page has loaded.

Send response multiple times?

I have a little problem.
I have a node application on a server, that serves a website as control panel for a client based application.
Example:
You click a link on the site
A http request triggers the server to send a command via socket to the client
The client executes this command
The client sends the output of the command back to the server (socket)
That works fine, on time. The second time the server crashes because the header is already sent.
//Comand comes in
app.get('/create/:id/:package', function (req, res) {
if (io.sockets.connected[req.params.id]) {
//Command is sent to client
io.sockets.connected[req.params.id].emit('control', {type: 'create', packageName: req.params.package});
//Output is coming back
socket.on('createOutput', function (data) {
//Response sent back to http request (works once)
res.send(data);
});
}
});
Is there any way to work around this behavior?
You can send the data only once with socket.once:
socket.once('createOutput', function (data) {
//Response sent back to http request (works once)
res.send(data);
})

How to get entire request in node.js

I would like to get the entire request (header and body just as they appear when they arrive at the application) in Node.js. I'm able to get it by reading directly from the socket on connection (example below), but I haven't found a way to associate it with a particular request object as it's processed by the server.
...
var server = http.createServer(app).listen();
server.on('connection', function(socket) {
socket.on('data', function(data) {
console.log(data.toString());
});
});
...
app.get("/", function(req, res) {
//get the data that would be output from the above snippet in this context
//do something with it
});
This is just one example to illustrate what I'm looking for, I'm open to any method to achieve this other than attempting to reconstruct the request from information provided in the request object.

Categories

Resources