我有一个节点应用程序,它为我的react应用程序服务,如下所示:
// STATIC ASSETS WHEN PUSHED TO HEROKU
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
app.get("*", function(req, res) {
res.sendFile(path.join(__dirname, "./client/public/index.html"));
});
通常情况下,这应该是您放置的最后一条路线,因为它会覆盖所有其他的get路由。但是,我有一些中间件来检查身份验证:
const jwt = require("express-jwt")
const auth = jwt({
secret: process.env.JWT_SECRET,
userProperty: 'payload'
});
app.use("/auth", authRoutes);
app.use(auth);
app.use("/api", routes);
/auth
路由用于登录和注册,因此不受中间件的保护,而/api
路由则是。
但是,当我尝试使用该应用程序时,它没有正确地从API请求(如GET /api/users
)中发送数据,而是返回*路由中指定的HTML。
有没有办法让我有我的认证路线,并仍然服务我的反应应用程序正确?
发布于 2018-09-26 04:45:21
您可以将HTML路由放在底部,并且只使用auth
中间件创建API路由。这将不会对静态页面执行auth中间件,并且只授权/api
路由。
const jwt = require("express-jwt")
const auth = jwt({
secret: process.env.JWT_SECRET,
userProperty: 'payload'
});
app.use("/auth", authRoutes);
app.get("/api", auth, routes);
// STATIC ASSETS WHEN PUSHED TO HEROKU
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
app.get("*", function(req, res) {
res.sendFile(path.join(__dirname, "./client/public/index.html"));
});
https://stackoverflow.com/questions/52509761
复制相似问题