5

I have an AngularJS app on a NodeJS server with ExpressJS. Now I am serving an Angular app as static files:

app.use(express.static(__dirname + '/app'));

But in navigation, I have a # sign:

http://127.0.0.1:8080/#/queryes

To solve this problem, I put this code in the Angular Router:

$locationProvider.html5Mode(true);

But now I can't get partial views. How do I mix Angular Routes with ExpressJS?

1

1 Answer 1

22

In order to use AngularJS html5mode along with Express, you must serve "index.html" for all requests to leave all routing up to AngularJS. I had this same problem a while back.

So first, you declare all API endpoint routes, any static file directories (CSS, JS, partials, etc), and then serve index.html for all remaining requests. For example:

    // serve all asset files from necessary directories
    app.use("/js", express.static(__dirname + "/app/js"));
    app.use("/img", express.static(__dirname + "/app/img"));
    app.use("/css", express.static(__dirname + "/app/css"));
    app.use("/partials", express.static(__dirname + "/app/partials"));
    app.use("/templates", express.static(__dirname + "/app/templates"));

    // any API endpoints
    app.post('/api/v1/auth/login', routes.auth.login);

    // serve index.html for all remaining routes, in order to leave routing up to angular
    app.all("/*", function(req, res, next) {
        res.sendfile("index.html", { root: __dirname + "/app" });
    });
Sign up to request clarification or add additional context in comments.

4 Comments

I also have api folder both app folder and now is conflict.
I'm sorry, I'm not sure I understand your question. Can you update your original question with a code sample/error message?
I have also on my www.myapp.com/api/ my API. And this code not works for api routes.
Your API routes need to all be defined above the app.all call. In my example, the app.post is an API endpoint example.

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.