"Cannot GET" nested state with AngularJS ui-router, html5Mode, and Express - javascript

Currently I'm trying to get $locationProvider.html5Mode(true) working with AngularJS, ui-router, and ExpressJS. Given an abstract state parent with URL /parent and a nested state parent.child with URL /child, navigating to localhost:3000/parent/child within the webpage itself works just fine. However, when refreshing the page on the same URL (or typing the URL directly into the address bar), the browser returns a message "Cannot GET /parent/child".
We've been trying a few different configurations and such with ExpressJS and middleware. These setups do not solve our problem:
app.use(express.static(__dirname + "/public"));
app.get("/", function(req, res, next) {
console.log(req.url);
res.sendFile(__dirname + "/public/index.html");
});
returns the "Cannot GET" error.
app.use(express.static(__dirname + "/public"));
app.get("*", function(req, res, next) {
console.log(req.url);
res.sendFile(__dirname + "/public/index.html");
});
floods the (Chrome) Developer console with the error Uncaught SyntaxError: Unexpected token < for every js file, since Express is sending index.html for requests for js files within index.html using the <script> tag.
When navigating to a URL like localhost:3000/parent, the webpage displays just fine without any errors.
Update: I should mention that the request URLs for .js files are turning out to be /parent/js/someJsFile.js, for example, when refreshing localhost:3000/parent/child.

It is common practice to keep your static resources in a location that can be isolated and served with the static middleware (for this very reason).
Recommend
Move your static assets (i.e. js files) into a location specified for static resources.
Then, the second configuration above is the fix:
app.use(express.static(__dirname + "/public/static")); //<-- JavaScript here
app.get("*", function(req, res, next) {
console.log(req.url);
res.sendFile(__dirname + "/public/index.html");
});
Alternatively
You could employ the urlrewrite middleware to accomplish your goal: https://github.com/kapouer/express-urlrewrite

Related

Express app.get() code in server not updating but other server code will update

I have a node js and express server I run on localhost. Recently, while changing the server code from
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
to
app.get('/', (req, res) => {
res.send('home');
});
The server still serves the "index.html" file and does not send the message "home". I also tried deleting all my "app.get()" and "app.post()" functions and it still runs as it was before the changes. I have double checked that I saved the file and restarted the server but even then, still does the same thing. The odd thing is that when changing anything else in the server code aside from my express code it runs as expected.
I tried searching my problem but no one is experiencing the same issues. Any help is appreciated, thanks.
All of your code is not listed, so this is an educated guess, but I would check to see if you are using express.static or another package to serve the directory your index.html file is in via app.use() before your routes. By default express.static will serve index.html if presented a root path ('/').

React router browser history with server routing

I am writing a web application using react for client side and express for server side.
I am using react-router (link) routing the client pages.
Working with the hashHistory it was simple and worked fine, but now I want to use browserHistory.
As mentioned in the react-router tutorial, I need to tell my server to expect the client request, so when we render a client page it will server the index.html.
I can't find a way to handle both requests from the client for pages and requests for server processing.
For example, I have a page in the path /product, but I also have an endpoint for the server processing /authenticate.
In the react-router tutorial it says to use the following:
// server.js
// ...
// add path.join here
app.use(express.static(path.join(__dirname, 'public')))
// ...
app.get('*', function (req, res) {
// and drop 'public' in the middle of here
res.sendFile(path.join(__dirname, 'public', 'index.html'))
})
But this way will result every request (including /authenticate) to send it back to the index.html. How can I merge those two?
You have to define the /authenticate before the * (which is basically a Catch-All and has to come last)
app.use(express.static(path.join(__dirname, 'public')))
ap.get('/authenticate', function (req, res) {
res.sendStatus(200)
});
// ...
app.get('*', function (req, res) {
// and drop 'public' in the middle of here
res.sendFile(path.join(__dirname, 'public', 'index.html'))
})

Troubleshooting node.js error

I just inherited a node.js project, where I'm suspicious that some of the original boilerplate necessary for a node project hasn't been finished. This is also my first time using node.js.
Anyway, when I run node app.js, the correct port boots up and everything, but the app can't load a number of the script files (the error "Uncaught SyntaxError: Unexpected token <" is given on each js file unable to be loaded). I've tried to troubleshoot this error, there are a lot of resources online for it, but I haven't been able to nail it down. I tried adding type="text/javascript" to each of the script tabs but it didn't change anything.
When I click to troubleshoot the incorrect loading paths of the scripts, they all bring me to the index.html page. Thus, for some reason, it seems like this section of the code from the app.js file isn't working:
// serve all asset files from necessary directories
app.use('/js', express.static(__dirname + '/public/js'));
app.use('/css', express.static(__dirname + '/public/css'));
app.use('/partials', express.static(__dirname + '/public/partials'));
app.use('/lib', express.static(__dirname + '/public/lib'));
// JSON API
app.get('/api/name', api.name);
// redirect all others to the index (HTML5 history)
app.all('/*', function(req, res, next) {
res.sendfile('index.html', { root: __dirname + '/public' });
});
However, it looks like it should be working properly (following the paths of the files). Any ideas?
Almost certainly the app.all route is sending back HTML for a request that should be sending javascript. You need to look at the specific URLs that the browser is fetching as script tags but the server is sending back HTML. The corresponding .js files probably are just not there under public/js which causes the router to proceed to the catch-all route.
Side note you can compress your express.static routes to just this because of how your URLs line up with the filesystem structure.
// serve all asset files from necessary directories
app.use(express.static(__dirname + '/public'));

Passport.js express views

I'm using passport and some static .html files. I want to include them as express views or static files. Now I want SOME .html files like login.html to be available for everyone, but the other view files like secret.html should need passport.
I know, that you can use
app.get('somePath', ensureAuthenticated, function (req, res, next) {} for routes, but I want it for static files.
How to do it on a non-hacky way?
If all "secure" files share a distinct URL prefix, such as /public/secure, you can use() ensureAuthenticated with this path:
app.use('/public/secure', ensureAuthenticated);
app.use('/public', express.static(__dirname + '/public'));
Otherwise, the express.static() middleware doesn't offer many options for controlling access. For the most part, it assumes all available files from the path given to it are meant to be "public."
Though, it does normally refuse to send hidden files, following the *nix standard of a . prefix:
~/path/to/.secret.html
Then, to actual serve it, you can send the file yourself in the route you suggested with the middlware attached:
app.get('/path/to/secret.html', ensureAuthenticated, function (req, res) {
res.sendfile(__dirname + '/path/to/.secret.html');
});
And, you may want to consider moving it out of your static() directory,

In express router method is not working if i serve static files

In my node application first i want to serve my static files and then using router method depending upon the incoming request i will query the DB and get the body of the html page then i will send this body content to the client side and finally using Backbone.js i will render this body in my html page.Now what is my problem means express router method is not working if i serve static files.But if i remove the below line means my router is working.
app.use(express.static(__dirname + '/public'));
app.js
var express=require('express');
var app=express();
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
console.log('router called successfully...');
res.send('body of the page');
res.end();
});
app.listen(8011);
app.use(express.static(__dirname + '/public'));
Your unnecessary anonymous function is screwing up how the middleware is supposed to work. The above line is in 95% or more of all express sample apps. Not sure why you decided to deviate from that, but your version is a useless middleware that creates a static middleware and immediately discards it.

Categories

Resources