How to dynamically render/load pages in express? - node.js

I need to dynamically load/render part of a page in nodejs (v1.8.15) with express (>3.0) framework. Generally, I want to create a single-page app.
I have a menu at the top of the page with links. Clicking on the links will change the content below, as in AJAX page loading.
For example:
>home|login|signup|chat
..content for home..
If I press the 'signup' link:
home|login|>signup|chat
..content for signup..
In express I have routes on the server:
var express = require('express');
var app = express();
app.get('/signup', function(req, res) {
// render signup.jade
res.render('signup');
}
app.post('/signup', function(req, res) {
// .. work with information
if (ok) res.send('ok', 200); else res.send(error, 200);
}
After reading this, I figured out that I should use socket.io. I know sockets well, so it will be easy to send data about 'clicking on link' from the client to the server.
Q1: How do I render/load pages dynamically like I wrote in express?
Yes, I could use AJAX for page loading, but will it work for .post methods in express?
How should I organize my thoughts to create such a site?
By the way, I've read about Derby and SocketStream, but I didn't understand.
Q2: Can I use Derby or SocketStream in my aims (site functions: login, signup, chat)? How?
If SocketStream is what I need, that would be very bad, because Heroku doesn't work with it.

Q1) This is in fact very simple, no need for Socket.io, Derby or whatever. You can call any expess route with any method through ajax, using jQuery makes ajax very easy. In your example, let's suppose your container HTML file has a div with id 'container', which is where you want the ajax-loaded content to go:
$.ajax({ url: 'http://yoursite.com/signup'
, type: 'GET'
, dataType: 'html'
})
.done(function(data) {
$('#container').html(data);
})
.fail(function() {
console.log("Something went wrong!");
});
Express supports all HTTP verbs (GET, POST, PUT etc.). For loading pages dynamically, use GET, then when a user enters some login information you can POST it to an Express route that will tell you if it is valid or not, and you use jQuery to modify the DOM accordingly.
Q2) As said in Q1, no need to use Derby or SocketStream. Plain old jQuery + basic Express will get you where you want!

Related

External web service redirects the user and posts data to my callback URL. How do I render the posted data to the user in an Express/Next.js app?

Any help would be hugely appreciated! Been stuck on this for a few days.
I have an Express/Next.js app where:
I send the user to an external website
user makes a payment
external website redirects and posts data back to my callback URL.
So now I have the user on a mysite.com/payment-complete route but also want to display the data that was sent back.
I have an app.post endpoint to successfully grab the data:
app.post("/payment-complete", async (req, res) => {
const transactionID = req.body.trans_id;
});
How would I pass the data to the user who is already on that route? Or pass the data before the page is rendered?
The flow of data is third party > my server > user and I'm not sure how to make this work.
I'd be grateful for any help/direction with this.
If anyone comes across this - the problem was that in Express (and other languages) you can't redirect or render a view for an AJAX POST request but you can if the POST request is coming from a submitted html form. The web service was in fact POST-ing the data and redirecting my users with a form and so I could render a view.
Following code worked using Handlebars templating engine to send the render.
router.post("/payment-ok", async (req, res) => {
const transactionID = req.body.trans_id;
return res.render("rendertest", { id: transactionID });
});
Should also possibly work with app.render to send a Next.js view instead, but I wanted to render from a separate routes file.

How to make Express return a new html with axios post

I have an express server. I have two routes as get methods.
app.get('/main',(req, res) => {
res.sendFile(`main.html`, {root: staticPath});
});
app.get('/signin', (req, res) => {
res.sendFile('signin.html', {root: staticPath});
});
I want to build my app as a single page react application. But before I let the user see this single page, I want to show a sign in, sign up screen. So when user clicks the sign in or sign up buttons, I want to send signin.html as response from the express server.
Here is my code on the browser from a react class
SignIn(){
axios.get('signin');
}
I can console.log() from the express route and verify that the code gets executed within the 'signin' route, but the html view doesn't change on the browser even though I send back a html file. How do I make it happen?
I'm by no means an expert, but here are my two cents. Instead of setting up your front end to receive an HTML file from the server, a more efficient approach would be the following.
Build the signup and login pages on the front end.
Set up routing between these pages.
Send the login/signup details from client to server via /login or /signup routes that you set up in Express. These details would usually be in the req.body object (make sure to install the bodyparser package from NPM).
You could then use JWTs to authenticate users and maintain sessions.
If you're looking for server-side rendering with React, here is an article for your reading pleasure :) Sorry if I made no sense.

render page while making http request express

Hi i'm an express noob.... I have an api look page, that's all working but what i'd like to have is once a user hits the route i'll display a loading page, fire off the api http request then once it's successful redirect/render the results page. As i understand it you can't use res.render twice on the same route? Maybe our chum next(); can help here?
This is what i have so far:
router.get('/lookup/post/:url', function(req, res){
// Render the loading page...?
res.render('loading');
Lookup.post(req.params.url, function(err, result){
if(err){
}else{
// ...Then once the api lookup comes back ok redirect or render the results page?
res.render('results', {
posts : result.store.postData.posts[0],
votes : result.store.voteData
});
}
});
});
The solution to your problem is to do part in the UI and part on the server. You can do it with an Ajax call or by using Socket.IO, which will create a socket connection to the server.
I would argue that the later is the most convenient solution, because you can talk to the back-end and the front-end by emitting and listening to messages. The cool part of Socket.IO is that if the browser doesn't support sockets, it will default to an Ajax call.
The official website of Socket.IO is: http://socket.io. You can also check my bPhone project where I use Socket.IO in the simplest way possible. Plus my code have a lot of comments that should make everything super clear.
I hope this will put you on the right path :)

SailsJS - How to render views in server

Can please someone let me know how to render all the views in the server and send it to the web browser ? Just like any other PHP framework would do ?
Is this feasible at all ?
Read through the Sails.js documentation.
In the controllers section you can learn about the Response Object. On the response object you have a function called view().
So you can use res.view() to render a view and send it to the client. Typical example:
functionNameHere: function(req, res, next) {
res.view({
data: {first: "one", second: "two"}
});
}
Sails.js is built on top of Express.js. There are already plenty of tutorials on how to use Express on the internet.
Here is the documentation for Express.
Just put:
YourFunctionName : function (req,res) {
res.view('yourview', option, data);
}
The parameters are optional depending on the way you need and you put your route.js file.
Read the controllers section on: http://sailsjs.org/#!documentation/controllers

How do I update A Jade Template form an ajax post?

I have set up a basic node.js web-app using express with the default view engine jade.
When the User first loads the page the following occurs
app.get('/', function(req, res){
res.render('index', {
title: 'Test',
mode: "user"
});
});
What i cannot work out is how to then change the parameter I initially passed into the jade template from a ajax call.
app.post('/', function(req, res){
console.log(req.body.list);
res.redirect('back');
// I imagine the code needs to go here and look somewhat like the following
//
// res.?update-view({
// mode: "admin"
// });
});
If anyone has had experience with this working your input would be appreciated.
I'm not exactly sure what you're after, but if it's updating the page with the results of an AJAX call (which does not refresh or otherwise reload the page) then you'll have to use client-side JavaScript. jQuery's load() or post() should be able to handle that.
Alternatively, if you are not using AJAX but instead performing a normal form submit, you have a couple of options. One, you can keep your redirect in and use Express/Connect's Sessions system to determine what is used for the get request, or two you can replace the redirect with another res.render of the index.jade page and include the variable you want to change.
It should be understood that after either of these takes place, node.js relinquishes control of the web page to the browser, unless you specifically set up architecture for communication. There are currently no controls in node.js to force updates or page changes down to the client. Except via socket connections or unless otherwise polled by the client itself (such as in the first example involving jQuery).
Assuming you want to display the same page, with other "mode"
// set the page title for all requests
app.locals({ title: 'Test' });
// GET request
app.get('/', function(req, res){
res.render('index', {
// displays the default "user" mode
mode: 'user'
});
});
// when POST is submited
app.post('/', function(req, res){
// this is the param given by the user
console.log(req.body.list);
// now render the same page
res.render('index', {
// with mode set to the the given parameter
mode: req.body.list
});
});
You could use something like the following, or if you want to use an AJAX call use jQuery ajax as long as there is a response
Client
script(type="text/javascript")
$(document).ready(function(){
//...AJAX here....
var newValue = #{value} + 10;
});
Server
app.get('/ajax', function(req, res){
//This is where your code and response go
});

Resources