Using module export to mimic app.post and app.get - javascript

The application that I'm currently working on has been a bit difficult to apply information I've gotten from tutorials to. This app uses Express, but also features a lot of proprietary middleware that I don't quite fully understand.
My question relates to a particular way of utilizing app.get and app.post in our application. There isn't really a single point anywhere in the app that we use either of those things in that particular way, instead, each controller that we use features a module.export with GET and POST as the keys, which then contains all the code you would want to use for each request. All of this is wrapped up in a middleware that's based off of Tower.js (basically links the controllers to the views based on file path and name).
This has proved to be a bit troubling with trying to interpret tutorials where the code uses something like
router.post('/s3', multer({ dest: './uploads/'}).single('upl'), function(req, res, next){
client.putFile(req.file.path, '/user.jpg', function(err, response){
if (err) console.log(err)
res.status(200).send({url: response.req.url})
});
Is there any way to re-interpret this if the POST function in my controller for my route is used like this?
module.exports = {
get: function(req, callback){},
post: function(req, callback){}
}
(P.S. Yes, I'm having trouble using multer to upload images to S3 within this application)

Related

setting up a lot of routes in node.js

I've created a webpage to use it locally as a way to save information about random topics and college stuff. I have a ton of routes like the ones shown below:
//app.js - using node and express
app.get('/page1', function(req, res){
res.render('page1');
});
app.get('/page2', function(req, res){
res.sendFile('views/page2.html', { root: __dirname });
});
Each one of these routes has a .ejs file or a .html file, and they are all quite small.
I don't think I've made any major mistakes, but I gotta a feeling I'm not using "best practices", or at least could be doing some differently.
Is there anything wrong with using a lot a routes like this? Should change something to optimize the rendering of my pages?
As I said before, I'm using .ejs on most of the pages, and most of them have the same header.ejs and footer.ejs. Every time I change pages that have the same header/footer, do they get loaded again, or since they are using the same header/footer files the server only requests the content in between?
what's the difference between using res.render and res.send?
Should I be using a different syntax: const express = require('express'); & const app = express(); instead of var express = require('express'); & var app = express();
``` or this
app.get('/page1', (req, res) => {
res.render('page1');
});
```
Instead of the first block of code above.
Thanks! :D
Is there anything wrong with using a lot a routes like this? Should change something to optimize the rendering of my pages?
Nothing technically wrong with it. Many plain res.sendFile() routes can probably be replaced with a single express.static() middleware statement to simplify your code.
Lots of res.render() routes that don't pass any customized data to EJS can also probably be replaced by a single middleware that handles either a whole directory of template files (and their corresponding routes) or a list of files. That would be a lot more DRY than spelling out each route separately.
As I said before, I'm using .ejs on most of the pages, and most of them have the same header.ejs and footer.ejs. Every time I change pages that have the same header/footer, do they get loaded again, or since they are using the same header/footer files the server only requests the content in between?
EJS caches templates in memory (unless you disable caching) so the header and footer templates won't get loaded over and over again from disk.
what's the difference between using res.render and res.send?
These are fully covered in the documentation. In a nutshell, res.render() supports your template engine and local data to feed to the template engine to allow it to add data to the template. res.send() just sends the raw content you give it.
Should I be using a different syntax: const express = require('express'); & const app = express(); instead of var express = require('express'); & var app = express();
It is considered a good practice to use const whenever the variable you are declaring should get its initial value and not be assigned to again. In addition to some coding safety, this also can sometimes allow the interpreter to do more optimizations when using the variable (since its value can't be changed).

GET vs POST for fetching HTML page

Am able to fetch html page properly using postman GET But getting error while fetching html page using POST using postman
Error details :
404 Not Found404 Not Found
We have frontend code on html/JS and backend code on nodeJS
This can happen for so many reasons. Check your imports, routes and request url.
Though it is not the way to get your html through POST method. Using GET method is the right way.
const express = require("express");
const router = express.Router();
router.post("/", (req, res, next) => {
res.render("index", { title: "Express" });
console.log(req);
});
module.exports = router;
It is good if fetch data using GET method only and if it is giving 404 Error then it means you might have not created any route with POST method. Same route with different method treat as different route like
1) GET http://example.com/fetch
2) POST http://example.com/fetch
are 2 different routes. You need to define each separately
I believe that for fetching data, GET is the preferred method and POST should be used to update server-side resources, not to retrieve them. If POST is returning 404, You may not have a POST route configured, or POST access may be disabled by itself through your server's configuration.
Usually the "GET" method is used when requesting the an html page, for example all the browsers, uses "GET" for requesting the landing page of any url.
Post usually is used to send data and logging in.
You need to create a route for POST requests to get the HTML.
I'm assuming that you must be using some kinda framework router like express-router to route your pages. In your router code, you would be having something like
app.get('/myHtmlPage', function(req, res) {
// some code
})
so you're getting your page back for making GET requests. You need to create a similar route like
app.post('/myHtmlPage', function(req, res) {
// some code
})
to get the same page for POST requests.

Express 4 + Angular 2 HTML 5 Routing Concerns

I am making a basic web app with Express 4 and Angular 2. Here, there is nothing specific to Angular 2 besides the fact I am using its HTML 5 router.
Here is the routing work flow of the app:
There are two main server side routing configurations of the app. Both look similar to this:
/* GET home page. */
router.get('/', authenticationHelpers.isAuth, function(req, res, next) {
res.render('index');
});
/* GET login page. */
router.get('/login', authenticationHelpers.isNotAuth, function(req, res, next) {
res.render('login');
});
These manage explicitly, the two cases in which a user routes to / and /login.
However if the user is logged in and is able to visit / to render the index express view, there are HTML5 routes the user can take advantage of. These include urls like the following:
localhost:5000/user
localhost:5000/profile
localhost:5000/profile/settings
The issue
Clearly there is no router.get('/user'), and there shouldn't be, as this is all front-end work done by the Angular 2 router. However, to enable linking that would allow a user to simply type localhost:5000/profile/settings, and have the site route you to the index file (given that you were logged in) and THEN route you (with angular 2's HTML 5 routing) to your own /profile/settingsI had to place this piece of code in my app.js:
app.all("/*", function(req, res, next) {
res.render('index');
});
This gives me a big problem though. If you are not logged in and you are given the link localhost:5000/profile/settings it will render the index view because it only runs the authenticationHelpers.isAuth function on the router.get('/') routing code above. I would also love to be able to throw 404 errors on routes that don't exist in express, or angular.
However in my mind, to enable this functionality express would have to know about all the HTML 5 routing options as well as the express routing options. To me, this breaks the separation of routing concerns because if I changed an HTML 5 angular route, I'd also have to make a change in express (most likely, view the solution below). I'd like all this functionality, but without this information leaking between route handlers however I simply don't see a way around it. If anyone could help me figure out a better way to do this that would be great! If the information sharing or angular routes with express routes is the only way I've developed the most optimized lean solution I could below:
Potential Solution
router.get(['/', '/user/', '/profile/*'], authenticationHelpers.isAuth, function(req, res, next) {
res.render('index');
});
Add this to the end of all routes
app.all("/*", authenticationHelpers.isAuth, function(req, res, next) {
res.render('index');
});
Should solve your problem

How to set user name as local variable available in all views in mean.io

I am using mean.io but for my reasons I cut out all the angular it has and replace with knockout.js. Also I want to notice that my application is not single page. I render pages from different views and require for each require.js module with knockout business logic.
That's about app I deal with and here is my problem.
For example if user is logged in I want to show his name in the header of my app. So, I need to set express app.locals after passport creates user session. The problem is I have no idea where does it happen. I find passport initialization, but don't know how to ger user name without using req.user object. So, what is the best way of doing it
Use a middleware.
app.use(function(req, res, next) {
req.user && (app.locals.user = req.user)
});

Pass req res objects into socket.io?

I am a little confused how I can interact with the socket when I need to pass in data from my routes file. I have the standard setup using node.js, express, mongodb etc.
I'll run my socket.io logic inside server.js, and I include the routes.js inside that file.
var routes = require('./app/routes');
In this case I need to run some io.sockets inside my routes.js file.
My question is what is a good way to do this? I could run that specific route inside server.js but that gets messy. If I were to use sockets in my routes.js do I need to re-require
var io = require('socket.io').listen(server);
That means I need to create a new http server object, and I don't like that since I am requiring this file in server.js, this seems like a counter-intuitive move to me.
So how do I make a request to the server and pass for example a user name?
Example:
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile', { user : req.user });
io.sockets.on('connection', function (socket) {
console.log(socket);
console.log(req.user); // Here I have access to the user and can pass that around in my sockets
});
});
I am also using route middleware, so I'd like to keep that in my routes.js, IDK I am just confused what I should do, hopefully someone understands my angle here?
Edit:
What about passing something into the routes?
routes.initialize(app, passport);
You can get the req and res objects directly in the socket by invoking socket.request (a Getter function which is available via __proto__). See docs.
I was then able to find req.user in socket.request.client.user.

Categories