Getting dynamic route url with Express JS causes favicon to disappear - javascript

I'm using express.Router(). Getting a dynamic route in the following way causes my favicon to disappear. (Where id is the dynamic part).
router.get('/collab/:id', isAuthenticated, function(req, res) {
Getting a non-dynamic route like this allows my favicon to load properly, all other things being equal.
router.get('/collab', isAuthenticated, function(req, res) {
Somehow in going from :id to the actual value, it forgets to include the favicon. Can't find similar questions using Google. Am I overlooking something?

Related

Why am I unable to load my css file after redirecting using express?

So I am using express and express-handlebars. Everything is working correctly in that when I go to a url that corresponds to a get method I have and it renders a page, evreything is fine it loads the page with the css file. I have a form with a submit button that when clicked will render a page with the css just fine. However, if I try to redirect first (upon clicking sumbit) and then render a page from the new redirected get method, it doesn't work. Instead I get an error: "The resource from [URL] was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).". Can anyone explain to me whats going on here.
Ok update. It works only if I specify this: app.use("/routes/:author", express.static("public")); . But do I really have to create a static folder for every redirect?
These are the three express use methods I'm using
app.use(express.static("public"));
app.use("/routes", express.static("public"));
app.use("/routes/:author", express.static("public"));
First I go to my form.hbs
router.get("/", (req, res) => res.render("form"));
Then I click submit which has a href set to "/form" and I send a parameter
router.post("/form", (req, res) => res.redirect(`/routes/${model.author}`));
Which redirects me to "/:author" and renders my data.hbs
router.get("/:author", (req, res) => res.render("data"));
This works fine now.
If however, I remove, for example
app.use("/routes/:author", express.static("public"));
The css file for data.hbs does not load and I then get the error I mentioned above.

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

"Double vision" with HTML5mode, Angular with ui router and Express

I am an absolute noob, so bear with me. I am developing an app with angular and express. I am using ui.router for the angular routing and express to serve the pages.
I've used the following lines to enable html5 mode, which has successfully removed the pound sign (#) from the urls, however when hitting f5, only the view gets loaded, and not the index which should wrap the view.
$locationProvider.html5Mode(true).hashPrefix('!');
$urlRouterProvider.otherwise('home');
I tried adding the following lines as suggested online, but now the ui router is loading the index page itself in the view (looks like 2 layers of an infinity mirror, if that makes sense).
router.all("/*", function(req, res) {
res.render("index", { user : req.user });
});
I've seen res.sendfile used in examples, but I haven't had any success with that, either.
How can I use Angular's ui router, and express in html5mode without breaking my page? I can gladly give more code if needed.
Edit: more info!
Express serves the index page when '/' is requested.
router.get('/', function (req, res) {
res.render('index', { user : req.user });
});
The index page simply contains
""
which in turn shows the contents of which view I want to show.
EDIT: I have uploaded my project to github. https://github.com/shhtephe/SurfacingSolutions
The files I think you'll most need to see are routes/index.js and views/index.ejs
Hope that helps.

Categories