2

I'm trying to get my express app to always return 'index.html' which is the layout file that contains my angular app scaffold.

In my angular app when i'm at route "/home" I want to be able to refresh the page, so to do that I need my router to return me index.html.

For my html routing i'm using the following - All of my templates (home.html) are stored in the /templates directory:

var express = require("express"),
    router = express.Router(),
    path = require("path"),
    root = path.join(__dirname, "../../");

router.use(express.static(__dirname + "/../../templates"));

router.get("*", function(req, res) {

    //Response options
    var options = {
        root: root, 
    };

    res.sendFile("layouts/index.html", options);
});

This is obviously affecting my REST API requests, in that they're not sending back index.html.

For example, I have an /islands api route which returns back 'Island' objects from my mongo db.

var router = require("express").Router(),
    Island = require("../../model/island");

router.get("/", function (req, res, next) {

    Island.findOne({user_id: req.user.email}, function (error, island) {
        if (error) { return next(error); }

        return res.json(island);

    });
});

This is now returning me index.html.

Here's how i'm using the controllers above incase that helps.

app.use(require("./controllers/api/static")); //Returning static assets

app.use(require("./controllers/api/views")); //This is where the get route for returning .index.html is stored

app.use("/api/island",require("./controllers/api/island"));  

I'm a little confused as to how I can get index.html only return for html requests, not requests made to my api.

3
  • Have you tried putting your other api routes before the * one? Commented Dec 6, 2015 at 12:02
  • Ha! I did think that but I overthought my order of 'use' statements. I use some middleware (api authentication) and (wrongly) assumed it would affect the html routes. Re-ordering worked. Since you were first, if you post an answer saying that I will upvote & accept :) Commented Dec 6, 2015 at 12:06
  • No worries, you can upvote answer below! Commented Dec 6, 2015 at 12:07

1 Answer 1

4

Check order of your routes, put the api routes before your sendfile ones.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.