Express Rewriting for Clean URLs in MEAN Stack Application with no index.html - angularjs

Like many other clean angular URL rewrites, upon refreshing the page on a clean URL like localhost:3000/profile I get the GET /profile 404 error. I have been trying to use an Express Rewrite to send the index.html file, but as far as I know, I don't have an index.html to send, as it's not rendered until the index.js route.
I tried the following in my app.js:
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('index.html', { root: __dirname });
});
and receive Error: ENOENT: no such file or directory, stat 'C:\xampp\htdocs\healthyu\healthyu\index.html'
My directory looks like this image here, and I can see there is no index.html file in the root directory. I have tried views/index.html, views/index.ejs, and views/index with no luck, and views/index.ejs actually prompted a download when I refreshed the page.
Is there a way to use Express to successfully rewrite the URLs, or will I be more successful with a mod-rewrite in an .htaccess file?

So what I needed to do was change all of my server requests that were API requests to use the /api prefix, so get /api/posts in order to reduce conflicts with get /posts which was the original API call and view name along with other conflicts.
My index.html is generated in my express routes/index.js file so I just needed to make sure I used that file whenever I tried to navigate to a different URL than the home entry point. The relevant parts of the code looked like the following:
var index = require('./routes/index');
var users = require('./routes/users');
app.use('/', index);
app.use('/api', index);
app.use('/users', users);
app.use("/*", index);

Related

How to load dynamic url as static with Zeit.co for nextjs app?

I have a nextjs app that where I have this on my server.js:
server.get('/recipes/:urlId', (req, res) => {
const actualPage = '/recipe'
const queryParams = { urlId: req.params.urlId }
app.render(req, res, actualPage, queryParams)
})
So basically whenever I try to reach /recipes/{something} it renders the page with queryParams.
This is used later to call an api that will reach for the actual recipe information before displaying it back to the user.
If the user navigate from within the application, it works fine and I can pass the parameters properly and everything works ok.
But if I get the url and paste it directly on the url, I get a 404 instead of the recipe.
Running locally it works fine, but when I deploy it to Zeit I get this issue.
Is there something I need to configure there? Does it use the server.js I have set on my app locally or it uses something else?
The problem is the url makes the server to search for the folder recipe and to search for the folder which you have passed the urlId.
There are two ways you can do this.
1) So you have to tell the server that do not look for the folder just redirect the url for any url to index.html page
Or
2) You can use the hash strategy to make the url have # location path
Check the other solution here Router not working.
Or You can add the htaccess file for the server side changes may not be possible

Sending all routes or paths to angular

In my node js app.js I want that whatever the url is it goes to my angular/html page i.e. begin.html, app.js resides in server folder and begin.html is in client folder of my project. It's like :-
-Project
----Server
---------app.js
----Client
---------begin.html
What should I type in app.js so that all the urls go to begin.html where i am using Angular routing?? I think its something like..
var begin=require('../Client/begin.html);
app.use('*',begin);
If you are going to just have all routes go back to that HTML page, then you could just use a web server like Nginx serve that directory statically.
It looks like you are using Express, but that is just a guess. If you want to make HTTP requests from your Angular side to your Node.js side then you will probably want the default response to return your HTML, but still be able to allow requests through. I would look at using the static method from express to expose a static directory while still allowing you to build other routes (i.e. api routes).
It might look something like this:
// Already created express app above
/*
This will default to using index.html from
your Client directory and serve any other resources
in that directory.
*/
app.use(express.static('../Client'));
// Any other routes
app.listen(3000); // Or whatever your port is
Or you could also implement it using the 404 error handler style and return your default file:
/*
This comes after all of your other
route and middleware declarations and
before the .listen() call
*/
app.use(function(req, res, next) {
res.sendFile(path.join(__dirname + '/../begin.html'));
});

creating my first nodejs,mongo, express angularjs app

I am setting up my first angularjs webapp using nodejs.
The one part i am not sure how to do is how to include my angularapp.js in my index.html?
currently i have
/public
index.html
/javascript
webapp.js ( my angular app js file)
/routes
myroute.js
app.js (my nodejs app )
my myroute.js has and it loads fine
router.get('/', function(req, res, next) {
res.sendFile(path.resolve('public/index.html'));
});
the problem is that i am note sure how to load my webapp.js
in my index.html i have
<script src = "/public/javascript/webapp.js"></script>
And this does not load. So what is the best way to do this. Should i create
a route for everything in /public/javascript/
how do other people do this or what is the best practice
thanks for any help
update....
i added the following to myroute.js
router.get(/javascript/, function(req, res, next){
res.sendFile(path.resolve('public/javascript/webapp.js'));
});
and the javscript file now loads but this is not the way to do it.
I got it now. I've been searching and looks like for security reasons you need to serve the javascripts and other files you wish to allow access to as static files. On app.js add this :
app.use("/static",express.static(__dirname+"/public/javascript"));
Where "static" is just a virtual path you create for an specific folder. Then change src on script:
http://localhost:port/static/webapp.js
or
/static/webapp.js
It worked for me
For more details you should check this out:
http://expressjs.com/es/starter/static-files.html

Issue after remove (#) hashbangs from routing in angular-ui-router

I have remove (#) hashbangs by $locationProvider.html5Mode(true) in ui-route.
and set <base href="/public/">
when I have tried to localhost:59940/public/#/home url # is remove and url look localhost:59940/public/home and getting home view.
but when I have tried localhost:59940/public/home url. I have getting 404 Not Found error.
help me for getting home view when try to access localhost:59940/public/home in browser.
The problem is that the browser resolves urls before your angular app responds, and indeed the resource for that route is not there. The solution I have used is to make your 404 route return the index.html page and use ui-router to handle real 404 cases. But another idea is to match all of the client routes to routes on your server which return the index.html.
To enable $locationProvider.html5Mode in angular, you also need to some side server changes.
Other then your static assets and apis path, all other routes should server index.html(your main SPA page) only.
See below code.
This is how you can do it in node.js using express server.
var app = require('express')();
app.configure(function() {
// Static files - all js, css, images, etc go into the static path
app.use('/static', express.static('/static'));
// If a static file is invalid so we send 404
app.use('/static', function(req, res, next) {
res.send(404);
});
// This route deals enables HTML5Mode by forwarding missing files to the index.html
app.all('/*', function(req, res) {
res.sendfile('index.html');
});
});
app.listen(3000);

AngularJS and Express Routing issue

I'm using AngularJS and ExpressJS and having an issue with routing. I saw many other posts but none of those solutions seemed to work. Here is my routes in Express:
module.exports = function(app, auth) {
//Api routes
var mycontroller = require('../app/controllers/mycontroller');
app.get('/api/dostuff/:id', mycontroller.getBlockByHash);
//Home route
app.get("/", function(req, res) {
res.render('index');
});
};
When I go to my root /, everything works as expected. ExpressJS serves up my index and angular picks up the rest. When I click a link /blocks, it works as expected since AngularJS picks up the route. But when I refresh, I get a 404 not found error.
I tried app.get('*' instead, but that gives me a completely different error where nothing loads.
I'm using Jade to create the basic page structure with Express. My Express config is:
app.use(express.favicon());
app.use(express.static(config.root + '/public'));
When using html5Mode the documentation says:
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
What it doesn't mention is:
You should exclude static assets like scripts/styles/images/fonts etc.
You should also exclude your Restful API.
Your case:
The error you got there is express serving html into script tags and the browser fails to parse them as a valid javascript.
Use express.static to serve static assets and then use app.get('*', for redirecting all other requests to your angular.js entry point (index.html).
express.js middleware order do counts!
express.static must be declared before app.router
Node.js / Express.js - How does app.router work?

Resources