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
Related
I'm coding my first "solo" nodejs webapp. Its based on a previous app (that I coded by following some kind of tutorial/course) which was an Express REST API that allows you to add/remove/update/list a Todo list. I've also implemented user authentication using jwt/bcrypt. All this is stored in a MongoDB database.
Also note that all the endpoints return JSON.
I'm now trying to add a front-end to the app. The API endpoints are at /api/endpoint1, /api/endpoint2, etc., and the views are rendered on /view1, /view2, etc. I'm doing this on purpose so that I can get the responses in plain JSON from the API, or show it in a webpage rendered.
I started by using jQuery's ajax to make the calls but I realized this was not the way I wanted to do this. I removed all the js scripts on my webpage and started working directly on the server, rendering the pages with the info fetched from the api.
This is what I have now:
server.js (main file) [sample]
// RENDER 'GET TODOs'
app.get('/todos', authenticate, (req, res) => {
let auth = req.cookies['x-auth'];
request({
url: 'http://localhost:3000/api/todos',
headers: {
'x-auth': auth
}
}, function (error, response, body) {
if (error || response.statusCode !== 200) {
return res.status(response.statusCode || 500).send('Error'); // TODO
}
let bodyJSON = JSON.parse(body);
res.render('todos', {
title: 'Todo App - Todos',
todos: bodyJSON.todos
});
});
});
// API endpoint to 'GET TODOs' (JSON)
app.get('/api/todos', authenticate, (req, res) => {
Todo.find({
_creator: req.user._id
}).then((todos) => {
res.send({todos});
}, (err) => {
res.status(400).send(err);
});
});
I don't know why, but all this looks weird to me. I'm wondering if this is how I'm supposed to do this. I mean, is this a good approach/practice on making a API+front-end node app ?
Also, I'm using an auth middleware twice: in the views and in the API itself. I guess this is OK?
It would probably be better to use React/Angular but this is such a small app and I just wanted to make a really simple front-end.
Just keep things simple.
If you go with server-side HTML rendering, you don't need a REST API, just drop it. You need an API in case of an ajax frontend or mobile app.
If you needed a combined approach (server-side rendering + mobile app or server side rendering with some ajax), at the very first step you would want to isolate your database querying code into a separate module (which is actually always a good idea) and use the module from your API and from your views directly, avoiding API usage from server-side views.
This way you will eliminate excessive auth and make debugging much easier, also your code will become cleaner, thus more maintainable.
Also, React is not that complex, i would definitely give it a shot :)
I'm quite new on node.js and now I'm learning socket.io.
I'm developing an app step by step so, at this time, I have an app that can login an user, do crud operation in mysql and mongodb and upload files, all these operations are manage with some web pages with HTML and javascript technologies launched directly from restify.
After that I'm tring to add socket functionality to, at this time, simple print who is online.
So, before I have something like:
server.get('/login', function(req, res, next){ ... });
and now I have something like:
socket.on("login", function (req, res, next){ ... });
but, naturally, req and res are undefined!
Are there the same objects into socket.io?
To my understanding, you want to pass values back and forth in your request and response using socket.io.
Yes it is possible to do that and you syntax should be something like this...
Using express.js:
io.on('login', function(req){
client.emit('response event', { some: 'data' });
Note: when using emit you send the data to everyone, you have other methods like .broadcast(), .to(), etc.. for other use cases refer to socket.io github for better understanding
And lastly, inside emit you define the function you want to call on the client side and the data you want to send to the client.
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 :)
How to Handle a Coinbase Callback in NodeJS to Recieve Instant Bit Coin Payment Notifications ?
Please I need example.
Note : I'm using SailsJS MVC Framework.
OK, based on your comment, I will give it a go.
I am assuming you have (or will have) an ExpressJs app.
UPDATE Sorry, I just noticed you're using sailsjs. The below should still be valid but you'll need to adapt it to work with the sails routing engine.
In your app, you need to define the post route:
// the app variable is the express js server
// name the route better than this...
app.post('/coinbase', function(req, res){
var data = req.body;
var orderId = data.order.id;
// etc...
});
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!