React + Express - маршрутизатор, отображающий данные JSON вместо компонента React в браузере - PullRequest
0 голосов
/ 09 июня 2019

У меня есть два похожих случая с разным результатом. Один из них представляет компонент рендеринга реагирования как HTML-страницу, а другой показывает данные json в браузере.

Вот страница с данными JSON, я имею в виду enter image description here

Как вы можете видеть на изображении выше, есть также сообщение об ошибке:

Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:3000/favicon.ico (“default-src”).


Вот коды экспресс и реакции, которые отображают результат, показанный на изображении выше:


Экспресс-настройки

import express from "express";
import bodyParser from "body-parser";
import path from "path";
import cors from "cors";
import user_router from "./routes/UserRoutes";
import auth_router from "./routes/AuthRoutes";

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("*", cors());

app.use("/", user_router);
app.use("/", auth_router);

// Let the things inside frontend folder loadable from browser under public path
app.use("/public", express.static(path.join(__dirname, "frontend")));

// No matter what browser ask, return the content
app.get("*", (req, res) => {
  res.status(200).sendFile(path.join(__dirname, "./index.html"));
});

export default app;

База данных и соединение с сервером

import app from "./express";
import mongoose from "mongoose";

const PORT = process.env.PORT || 3000;
const mongoClientURI =
  process.env.MONGODB_URI ||
  process.env.MONGO_HOST ||
  "mongodb://" +
    (process.env.IP || "localhost") +
    ":" +
    (process.env.MONGO_PORT || "27017") +
    "/mernloginsystem";

/* CONNECT TO MONGODB */
const db = mongoose.connect;
db(mongoClientURI, { useNewUrlParser: true });
mongoose.connection
  .on("error", () => {
    throw new Error(`Unable to connect to ${mongoClientURI}`);
  })
  .once("open", () => {
    console.log("Connected to %s", mongoClientURI);
  });
/* <-- end --> */

/* CONNECT To NodeJs SERVER USING EXPRESS */
app.listen(3000, err => {
  if (err) {
    console.log(err);
  }
  console.log(`Server running on port ${PORT}`);
});
/* <--end--> */

Экспресс-роутер

router.route("/email/verify/:emailtoken")
.get(authCtrl.mailFromToken)
.post(authCtrl.verifyEmail);

React Router

<Route path="/email/verify/:emailtoken" component={Verify} />

Контроллер

const emailtoken = (req, res, next, token) => {
  UserModel.findOne({ mailToken: token }).exec((err, user) => {
    if (err) {
      return res.status(400).json({
        Error: "Email token is expired!"
      });
    }
    req.userinfo = user;
    next();
  });
};

const mailFromToken = (req, res, next) => {
  if (!req.userinfo) {
    return res.json({
      error: "No user found!"
    });
  }
  return res.json({ email: req.userinfo.email });
};

const verifyEmail = (req, res, next) => {
  // console.log(req.userinfo);
  // check if token present in the url
  if (!req.userinfo) {
    return res.status(400).json({
      error: "The verification token is not valid. Please register first!",
      norecord: true
    });
  }

  if (Object.keys(req.body).length === 0 && req.body.constructor === Object) {
    return res.status(400).json({
      error: "Not enough data is supplied!"
    });
  }

  const user = req.userinfo;

  // Check for token expiration (substract date) <---
  const currentDate = new Date();
  const tokenAge = Math.abs(currentDate - user.tokenCreation) / (1000 * 60 * 60);
  console.log(tokenAge);
  if (tokenAge >= 20) {
    return res.status(400).json({
      error: "Token expired!"
    });
  }

  // compare token
  // activate user if valid
  if (user.mailToken === req.body.emailToken) {
    const activation = { confirmed: true, userActivation: currentDate };

    UserModel.findOneAndUpdate(
      { _id: user._id },
      { $set: activation },
      { upsert: true, new: true },
      (err, activated) => {
        if (err) {
          return res.status(400).json({
            error: "There are problem when attempting to update this user!"
          });
        }

        return res.status(200).json({ activated, success: "Verification succeed!" });
      }
    );
  }
};

Коды, которые отображают реагирующий компонент как HTML-страницу


Экспресс-роутер

user_router
  .route("/api/users/:user_id")
  .get(authControl.signedInOnly, UserControl.get_one)
  .put(authControl.signedInOnly, authControl.currentUserOnly, UserControl.update_one)
  .delete(authControl.signedInOnly, authControl.currentUserOnly, UserControl.delete_one)
  .post(authControl.signedInOnly, authControl.currentUserOnly, UserControl.move_and_delete);

React Router

<Route path="/profile/:user_id" component={Profile} />

Контроллер

// GET SELECTED USER'S DATA TO BE USED ON THE NEXT MIDDLEWARE
const user_id = (req, res, next, id) => {
  UserModel.findById(id).exec((err, user) => {
    if (err) {
      return res.status(400).json({
        error: "Cannot retrieve user with that id!"
      });
    }

    req.userinfo = user;

    next();
  });
};
    // GET ONE USER
    const get_one = (req, res, next) => {
      if (!req.userinfo) {
        return res.status(400).json({
          message: "Forbiddem!"
        });
      }
      console.log("get_one");
      return res.json(req.userinfo);      
    };



// MOVE AND DELETE
const move_and_delete = (req, res, next) => {
  if (req.userinfo === null) {
    return res.status(400).json({
      error: "That user does not exist!"
    });
  }

  if (!req.userinfo.comparePassword(req.body.password)) {
    return res.status(400).json({
      error: "Password not match!"
    });
  }
  const { _id, ...user_data } = req.userinfo.toObject();
  const moved = new UserModel_deleted(user_data);
  moved.save((err, result) => {
    if (err) {
      if (err.errmsg.includes("duplicate")) {
        return delete_one(req, res, "Cannot save duplicate data!");
      }
      console.log(err);
      return res.status(400).json({
        error: err
      });
    }
    delete_one(req, res, "Saved to database!");
  });
};
// END move and delete

// DELETE ONE USER
const delete_one = (req, res, message) => {
  let selected_user = req.userinfo;
  console.log("delete_one");
  if (selected_user === null) {
    return res.status(400).json({
      error: "That user does not exist!"
    });
  }
  UserModel.deleteOne({ _id: selected_user._id }, (err, user) => {
    if (err) {
      console.log(err);
      return res.status(400).json({
        error: "Something went wrong!"
      });
    }
    // console.log({ message, user });
    return res.status(200).json({ success: { message, user } });
  });
};

Только потому, что я добавил get метод, страница отображает результат json в браузере, а не реагирует компонент / html-страницу. В то время как другой также имеет метод get, но по-прежнему отображает HTML-страницу.

Почему они дают разные результаты в браузере, в то время как их шаблон похож и что показывает сообщение об ошибке выше?

...