Reputation: 954
I have a node.js backend with an express server. I would like to default all get requests to the angular app and use the angular routing to handle the requests. The express server would handle all of the api calls from the angular app. I have set up my express routes with all api calls at the top and the following code at the bottom:
app.get('*', function(req, res){
res.sendfile('index.html', { root: path.resolve(__dirname + '/../../app') });
});
This works great for the default home page but it does not work well if there is a faux folder. E.g.
www.example.com (works)
www.example.com/product1 (works)
www.example.com/products/1 (does not work)
My HTML file references scripts using the following structure:
<script src="scripts/app.js"></script>
When I try to access a url with a faux folder (www.example.com/products/1) I get the following error: Cannot find file ‘products/scripts/app.js’
It is trying to use the folder in the url to find the file. Is there a way to resolve this? Or should I use express for the routing instead of angular?
Upvotes: 2
Views: 4426
Reputation: 1323
Give the script (and CSS files) an absolute path in the HTML
<script src="/scripts/app.js"></script>
Upvotes: 0
Reputation: 8089
Try adding <base href="/">
into the head of your HTML document. This solved the same problem for me.
Upvotes: 3
Reputation: 16395
The angular-express-seed is great to get you started with angular and express.
app.js
app.get('*', routes.index);
routes.js
exports.index = function(req, res){
res.render('index');
};
You don't have to use jade. You can use any template engine you want or just static html files. Note that res.sendfile
doesn't cache the file and shouldn't be used in production. The seed also has an example to show the json communication between client and server.
exports.name = function (req, res) {
res.json({
name: 'Bob'
});
};
If you use express for the routing you'll lose the single page app feeling.
Upvotes: 2