【问题标题】:Express + Angular, always send index file for html requests, not api requestsExpress + Angular,总是为 html 请求发送索引文件,而不是 api 请求
【发布时间】:2015-12-06 11:55:40
【问题描述】:

我试图让我的快速应用程序始终返回“index.html”,这是包含我的 Angular 应用程序脚手架的布局文件。

在我的 Angular 应用程序中,当我在路由“/home”时,我希望能够刷新页面,因此我需要我的路由器返回 index.html。

对于我的 html 路由,我使用以下内容 - 我的所有模板 (home.html) 都存储在 /templates 目录中:

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);
});

这显然影响了我的 REST API 请求,因为它们没有发回 index.html。

例如,我有一个 /islands api 路由,它从我的 mongo db 返回“Island”对象。

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);

    });
});

现在返回给我 index.html。

这是我如何使用上面的控制器以防万一。

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"));  

我对如何让 index.html 只返回 html 请求而不是对我的 api 的请求感到有点困惑。

【问题讨论】:

  • 你有没有试过把你的其他 api 路由放在 * 之前?
  • 哈!我确实这么认为,但我过度考虑了我的“使用”语句的顺序。我使用了一些中间件(api 身份验证)并且(错误地)假设它会影响 html 路由。重新订购工作。既然你是第一个,如果你发布一个回答说我会投票并接受:)
  • 不用担心,您可以在下面为答案投票!

标签: javascript angularjs node.js express


【解决方案1】:

检查您的路线顺序,将 api 路线放在您的 sendfile 路线之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2019-06-30
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 2016-05-30
    相关资源
    最近更新 更多