【发布时间】:2017-11-10 15:58:55
【问题描述】:
我正在尝试使用 Express 和 create-react-app 进行路由工作。
我的目标是当 URL 为 / 时将用户定位到应用程序的主页,当 URL 与 /login 匹配时将用户定位到登录页面。
在我的server.js 中,我定义了两条路线:
var mainRoutes = require("./routes/mainRoutes");
var apiRoutes = require("./routes/apiRoutes");
[...]
app.use("/", mainRoutes);
app.use("/api", apiRoutes);
apiRoutes 包含所有 api 路由定义,mainRoutes 负责主导航(至少这是这个想法):
var express = require("express");
var path = require("path");
let router = express.Router();
router.route("/").get((req, res, next) => {
res.sendFile("index.html", { root: "./client/build/" });
});
router.route("/login").get((req, res, next) => {
res.send("This is the login page");
});
module.exports = router;
在某处我读到了关于提供由 create-react-app 的构建过程生成的静态资产的信息,所以我补充说:
// Priority serve any static files.
app.use(express.static(path.join(__dirname, "client/build")));
// All remaining requests return the React app, so it can handle routing.
app.get("*", function(req, res) {
res.sendFile(path.join(__dirname + "/client/build/index.html"));
});
添加这些行后,我成功地看到了我的 index.html,但我无法同时访问 /login 和 /apisubroutes,因为它每次都将我重定向到主页 (index.html)。
就像我需要在我的子路由 mainRoutes 上提供静态文件,但我不知道该怎么做。
我怎样才能做到这一点?
【问题讨论】:
标签: express url-routing create-react-app