如何在同一个域上拆分后端和前端?

时间:2021-02-02 12:57:19

标签: node.js express heroku routes react-router

我使用 React 和 Nodejs(Express) 开发了我的应用程序,并将它托管在 Heroku 上。我将它托管在同一个域下,以便 cookie 正常工作,因为我遇到了一些问题。问题是,现在当我通过我网站上的链接转到 www.mysite.com/login 时一切正常,但是一旦我刷新该 URL 上的页面或手动键入该 URL,我就会向我的 BE 发送 GET 请求并获得 404 (这条路线不存在)。

如何防止此类调用?

我使用 react-router 处理我的路由,如下所示:

const App = () => {
return (
    <Router>
        <Sidebar />

        <Switch>
            <Route path="/" exact component={Home} />

            <Route path="/important" exact strict component={Important} />

            <Route path="/lists" component={ListProtectedRoute} />

            <Route path="/register" exact strict component={Register} />

            <Route path="/login" exact strict component={Login} />

            <Route path="/logout" component={Logout} />

            <Route path="/api/*" component={Page404} />

            <Route path="*" component={Page404} />
        </Switch>
    </Router>
);
};

Page404 组件基本上使用路由和重定向将用户重定向到主页(“/”)页面。

我的快速路线如下所示:

app.use("/api/users", userRoutes);

app.use("/api/todo", todoRoutes);

app.use("/api/lists", listRoutes);

app.post("/api", [check("user_id").exists().notEmpty().isNumeric()], (req, res) => {
    const valErr = validationResult(req);
    if (!valErr.isEmpty()) {
        return res.send(valErr);
    }
    const user_id = req.body.user_id;
    const sql = "SELECT * FROM posts WHERE user_id = ?";
    db.query(sql, user_id, (err, result) => {
        if (err) throw err;
        res.send(result);
    });
});

如您所见,我使用 /api 前缀 进行 BE 调用。 这是我用于注册的调用 userContext.js:

const register = () => {
    Axios.post(`${apiUrl}/users/register`, {
        userName: nameReg,
        userPassword: passwordReg,
    }).then((response) => {
        const errors = response.data.errors;
        processErrors(errors);
    });
};

常量 apiUrl 如下所示:www.mysite.com/api

这是我在同一域中同时托管 FE 和 BE 的网站的链接:LINK -> 工作不正常

这是我在 2 个不同的主机(Netlify 和 Heroku)上分别托管 FE 和 BE 的链接:LINK 2 -> 这就是我希望它工作的方式

1 个答案:

答案 0 :(得分:0)

好的,我已经设法解决了

app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/public/index.html"));