Express:在子例程上提供静态文件

Express:在子例程上提供静态文件,express,url-routing,create-react-app,Express,Url Routing,Create React App,我正在尝试使用Express和create react app进行路由工作 我的目标是,当URL为/时,将用户定位到应用程序的主页,当URL匹配/login时,将用户定位到登录页面 在myserver.js中,我定义了两条路由: var mainRoutes = require("./routes/mainRoutes"); var apiRoutes = require("./routes/apiRoutes"); [...] app.use("/", mainRoutes); app.u

我正在尝试使用Express和
create react app
进行路由工作


我的目标是,当URL为
/
时,将用户定位到应用程序的主页,当URL匹配
/login
时,将用户定位到登录页面

在my
server.js
中,我定义了两条路由:

var mainRoutes = require("./routes/mainRoutes");
var apiRoutes = require("./routes/apiRoutes");

[...]

app.use("/", mainRoutes);
app.use("/api", apiRoutes);
虽然
apirouts
包含所有api路由定义,但是
mainlouts
负责主导航(至少这是一个想法):

在某个地方,我读到了有关为创建react应用程序的构建过程生成的静态资产提供服务的内容,因此我添加了:

// 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
/api
子例程,因为它每次都会在主页(index.html)上重定向我

这就像我需要在我的子程序
mainRoutes
上提供静态文件,但我不知道如何做到这一点


我怎样才能做到这一点呢?

创建react应用程序我相信处理路由的方式不同,你无法将浏览器的路由连接到你想要服务的路由,因为你正在运行一个单页应用程序”,除非你使用服务器和js包进行通用路由。

app.get(“*”)
将匹配您拥有的每一条路线

你应该这样做:

var mainRoutes = require("./routes/mainRoutes");
var apiRoutes = require("./routes/apiRoutes");

[...]

app.use(express.static(path.join(__dirname, "client/build")));

app.use("/", mainRoutes);
app.use("/api", apiRoutes);

// If the app reaches this point, it means that 
// the path did not match any of the ones above
app.use(function(req, res, next){
  // redirect the user to where we serve the index.html
  res.redirect('/');
});

它与html页面路由不同,您实际上运行的是一个页面,该页面使用javascript:D确实更改了内容,希望这对您有所帮助:>“我的目标是在URL为/时将用户定位到应用程序的主页,在URL匹配/登录时将用户定位到登录页面“当url匹配/通过用户点击应用程序或JS登录时,或者当他们在浏览器中键入url时,我相信当前的行为是使用hashrouting,但这看起来很难看,或者是通过服务器呈现react代码的通用呈现。两者都有缺点,但我认为这将引导你走上正确的道路。我什么都不知道。。如果有人知道某个解决方案,我会在添加
app.use(express.static(path.join)(\uu dirname,“client/build”))后立即听到它行,我无法访问
/login
页面和
/api
路由。我总是被重定向到主应用程序。
var mainRoutes = require("./routes/mainRoutes");
var apiRoutes = require("./routes/apiRoutes");

[...]

app.use(express.static(path.join(__dirname, "client/build")));

app.use("/", mainRoutes);
app.use("/api", apiRoutes);

// If the app reaches this point, it means that 
// the path did not match any of the ones above
app.use(function(req, res, next){
  // redirect the user to where we serve the index.html
  res.redirect('/');
});