Express not working as expected - javascript

I am trying to set up a react app with express running. However, I can't understand why it won't load the page I want it to
this is my app.js:
var express = require('express');
var app = express();
app.use('/', express.static('public'));
app.get('/', function(req, res) {
res.sendfile('./index.html');
});
app.get('/canYouPlay.js', function(req, res) {
res.sendfile('/canYouPlay.html');
});
app.listen(process.env.PORT || 8080);
This works. however if I change the first app.get to:
app.get('/', function(req, res) {
res.sendfile('./canYouPLay.html');
});
It still renders the same HTML file even when restarting the app even though they are different files.
also when i run this function:
handleClick: function() {
document.location.replace('./canYouPlay');
},
it says it cannot get /canYouPLay even though a HTML and js file exist with that name.
what have I missed or doing wrong?

Related

A routing problem with workbox vuejs in production and express

I am creating a forum application to learn about VueRouter in Express. What I am trying to do is create a routing in vuejs and then take it to production. When I compile everything works fine. The view files go directly to the public folder in express and work almost perfect. I can change the route perfectly but when I touch CTRL + F5 from a different route to the main one, it returns a GET error.
For example this is my index and work perfect:
I can even change the route:
I touch F5 and reload the page without any problem, but when I touch CTRL + F5 to make the request again, obviously it returns an error because I don't have the route declared in express,
but vuejs returns only one html index as a view, I can't render any other files because they don't exist.
These public folder at image are the files created by vue by the build command:
This is my express configuration:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersNotifications = require('./routes/notifications');
var usersNotifications = require('./routes/notifications');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/notifications', usersNotifications);
module.exports = app;
this is my index route on express:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
The only option I have is to render the only index that vuejs offers. How can i Fix that?
The other problem is that I would not like these console workbox messages, how can i remove them so they never appear:
and this is the vuejs registerServiceWorkers.js file:
/* eslint-disable no-console */
import { register } from 'register-service-worker'
if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
/***
* Note that here were some methods also display messages
* on the console and I deleted them. Methods like
*/
})
}
Any ideas?
Since vue router is handling page routing, you'll have to render index for all requested paths like:
router.get('*', function(req, res, next) {
res.render('index');
});
// in server
app.use('*', indexRouter);
If you're exposing other endpoints from server you'll have to mount this as the last route middleware like, say in your case:
app.use('/notifications', usersNotifications);
app.use('*', indexRouter);

node js routing with ejs res.render does not work, but res.send does

I am setting up the environment for a node js app.
But the views/ejs files are not being rendered. If i do:
app.get("/", function(req, res){
res.send('Something');
});
This works. But, if I do(having an index,ejs file):
app.get("/", function(req, res){
res.render(index);
});
It does not work, I get "index is not defined" on the cleint side in the web, but no error in the command line.
Here is the app.js:
var express = require("express");
var path = require("path");
var app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.get("/", function(req, res){
res.send('Something');
});
app.get("/", function(req, res){
res.render(index);
});
const port = process.env.PORT || 3000
app.listen(port, function () {
console.log(`Express is running on port ${port}`)
})
IS there something wrong with the app.set parameters, or has something changed? I am following a tutorial which might be out dated, but checking the docs, I do not see an issue.
So, what is wrong here, is there a new way to do the routing with ejs? I know partials are gone now. Does this mean no ejs files at all anymore, and if so, how is it supposed to be done now? By rendering an html file?
Thanks
Well, I'm not a pro of express but here index is not defined because you write it like a variable. Try using something like this
res.render(path.resolve(__dirname + "/views/index"));

Route an entire folder and its content

I want to protect a folder and its content by redirecting the user back to index.
I've tried this, but it only works partially.
var express = require('express');
var path = require('path');
var http = require('http');
var app = express();
app.set('port', 8080);
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'views')));
app.get('/', function(req, res) {
res.render('index.ejs');
});
app.get('/protected/*', function(req, res, next) {
res.redirect('/');
next();
});
//activating server
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
This routes, for example, "localhost:8080/protected" and "localhost:8080/protected/asdf", but not "localhost:8080/protected/otherPage.html".
In this case asdf is not an actual file, but otherPage.html is. So if the file is there it doesn't redirect, but if it is not then it redirects. Why is this?
Your line dealing with static files app.use(express.static(path.join(__dirname, 'views'))); appears before app.get('/protected') so its being matched first.
If you moved the static handler to later in the code this would work as you require.
However, I would recommend splitting the static items into a separate folder to guard against accidentally revealing any server-side code you might be including in ejs files in the views folder.

Using Route of express node.js but express.Router getting as undefined

My code of router from default routes/index
/* GET home page. */
exports.index = function(req, res){
res.render('user', { title: 'Abcd' });
};
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
router.get('/helloworld', function(req, res) {
res.render('helloworld', { title: 'Hello, World!' })
});
module.exports = router;
getting error as can not call method get of undefined.I am new in node js please anyone help me.
Try upgrading to Express 4.x. You are probably running a 3.x flavor.
Router is a middleware of express which is registered implicitly with the express object the first time post() or get() is used. You can but don't have to add this explicitly calling use(), which allows you to register various middleware with express and so allows configuring processing and behavior in consideration of precedence.
Correct initialization and usage might look like this:
EDIT: Changed the example to be a "complete" http server.
app.js
var http = require('http');
var express = require('express');
// Requiring express exports a function that creates the application. Call it!
var app = express();
// Set port to listen to
app.set('port', process.env.PORT || 3000);
// Set view engine
app.set('view engine', 'jade');
// Tell express to use the router middleware
// Can be omitted if precedence doesn't matter
// (e.g. for loading static resources)
app.use(app.router);
// Add callback handler for home (/) route
app.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
// Create http server by passing "app" to it:
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
Now, if you place a minimal view into the default folder for views...
views/index.jade
doctype 5
html
head
meta(charset='utf-8')
title #{title}
meta(name='viewport', content='width=device-width, initial-scale=1.0')
body
div
h1 Gotcha! Title is "#{title}"
... and start your server from the console with...
$ node app.js
...you should have your first node/express/jade powered app up and running!

Default route in Express.js

I'm writing an application with node.js and express.
I have setup a default route as this :
app.get('/', function(req, res){
res.sendfile('./views/index.html');
});
This works fine when I goto /localhost:port/
But in the URL when I type anything after that, /localhost:port/blah I get 404 ERROR which makes sense.
I want to setup a default route so that no matter what I type in the URL after localhost:port/ it should all get back the same html file.
I tried changing / to * :
app.get('*', function(req, res){
res.sendfile('./views/index.html');
});
but after I do this I start getting this error in the console and nothing shows up:
Uncaught SyntaxError: Unexpected token <
in all of my Javascript files: :3000/scripts/myscript.js:1
somehow my javascript file show the content of HTML
===EDIT====
I used this and it worked fine for first level urls: like loclhost:port/blah
app.use(function(req, res){
res.sendfile('./views/index.html');
});
but when the URLs are multilevel, I see the same problem as described earlier localhost:port/blah/foo
The problem here is that router is looking for public directory under /blah folder for all the javascript and CSS files in this case, which does not exist. And it's returning the default HTML file. How do I fix this?
==================EDIT POSTING THE WHOLE CODE =========================================
var http = require('http');
var express = require('express');
var api = require('./routes/api');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/mydb');
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
app.get('/api/user/:userid', api.getUserInfo);
app.get('/', function(req, res){
res.sendfile('./views/index.html');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
In addition to this, I have an HTML with a myscript linked in it,
<script type="text/javascript" src="./scripts/myscript.js" ></script>
Add this route at the after of all your previous routes
app.get('*',function (req, res) {
res.redirect('/');
});
This will redirect any route not handled to the index "/"
As stated here, you can add this middleware just after your routing logic:
app.use(function(req, res){
res.send(404);
});
You might find this answer also useful.
Of course, you need to adapt the res.send() part to meet your needs.
With the newer version of express I would suggest using res.sendStatus as res.send has been deprecated.
Express v3
app.use(function(req, res){
res.send(404);
});
Express v4
app.use(function(req, res){
res.sendStatus(404);
});

Categories