express.json()在生产中不起作用

时间:2020-02-21 08:58:21

标签: node.js reactjs express heroku

我有一个NodeJS和React项目。我有问题。我不明白问题是什么。首先,我想向您展示我的问题所在。

在本地主机上。我想在heroku上这样,但是它让我成为下一个 enter image description here

我的问题的照片:

enter image description here

正如您在照片上看到的那样,在Heroku部署中,我的用户对象中有一个html文件。

但是当我在localhost上启动项目时,用户有一个来自mongo数据库的对象。 Express.json()正在localhost上正常运行,但在Heroku上不起作用。为什么会发生?我怎么了?

这是我的server.js文件:

const express = require("express");
const path = require("path");
const app = express();
const connectDB = require("./config/db");
const PORT = process.env.PORT || 5000;

connectDB();
app.use(express.json());

app.use(express.json({ extended: false }));
app.use(express.static("client/build"));

if (process.env.NODE_ENV === "production") {
  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "client", "build", "index.html"));
  });
}

app.use("/", require("./routes/quizRoute"));
app.use("/users", require("./routes/userRoute"));
app.use("/auth", require("./routes/authRoute"));

app.listen(PORT, () => {
  console.log("Server is started on the port " + PORT);
});

客户端请求

//SET AUTH WORK
import axios from "axios";

const setAuthToken = token => {
  if (token) {
    axios.defaults.headers.common["x-auth-token"] = token;
  } else {
    delete axios.dafaults.header.common["x-auth-token"];
  }
};

export default setAuthToken;

//加载用户

const loadUser = async () => {
    if (localStorage.token) {
      setAuthToken(localStorage.token);
    }
    try {
      const res = await axios.get("/auth");
      dispatch({ type: USER_LOADED, payload: res.data });
    } catch (err) {
      dispatch({
        type: AUTH_ERROR,
        payload:
          "AUTH_ERROR: Token dogrulanamadi veya /auth'a GET isteginde bir sorun var"
      });
    }
  };

enter code here

1 个答案:

答案 0 :(得分:1)

为什么遇到问题
我相信您的捆绑程序在为部署环境(即Heroku)构建时,会将NODE_ENV的值设置为production。因此,您遇到了这个问题,因为在每个get请求上,所有路由都会将您的客户端index.html发送回去:

if (process.env.NODE_ENV === "production") {
  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "client", "build", "index.html"));
  });
} 

因此,当您从客户端应用向/auth路由发出get请求时,此请求将被所有路由处理程序拦截,然后再进入所需的路由处理程序。我敢肯定,只要您对服务器进行任何get请求,您都将获得HTML字符串,而不仅仅是/auth

解决方案
为此,最简单的解决方法是让您将“包罗万象”路由移动到您的API路由下方,如下所示:

app.use("/", require("./routes/quizRoute"));
app.use("/users", require("./routes/userRoute"));
app.use("/auth", require("./routes/authRoute"));

// Every other API or similar routes should be before this catch-all
if (process.env.NODE_ENV === "production") {
  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "client", "build", "index.html"));
  });
}