Heroku部署了MERN应用,仅显示“未找到”

时间:2019-10-24 02:34:38

标签: node.js reactjs express heroku mern

我已经编写了一个MERN应用程序,它可以在本地运行并推送到heroku,但是当我转到heroku应用程序链接时,它只显示“未找到”。我已经检查了package.json构建脚本并添加了服务静态文件的快速路由,但是得到的结果是相同的。客户端文件夹位于根/后端文件夹内,并通过create-react-app创建。这是我的server.js:

const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const socketio = require('socket.io');
require('dotenv').config();

const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const cors = require('cors');
const expressSession = require('express-session');

const commentroutes = require('./routes/commentRoutes');
const postRoutes = require('./routes/postRoutes');
const userRoutes = require('./routes/userRoutes');
const messageRoutes = require('./routes/messageRoutes');
const searchRoutes = require('./routes/searchRoutes');
const statusRoutes = require('./routes/statusRoutes');

const User = require('./models/user');
const PrivateMessage = require('./models/privateMessage');

const app = express();

app.use(cors());

// parse application/x-www-form-urlencoded
app.use(bodyParser.json());

app.use(
  expressSession({
    secret: process.env.SECRET || 'local development secret',
    saveUninitialized: false,
    resave: false
  })
);

// ##### ROUTES #####
app.use('/user', userRoutes);

app.use('/post', postRoutes);

app.use('/comment', commentroutes);

app.use('/message', messageRoutes);

app.use('/search', searchRoutes);

app.use('/status', statusRoutes);

let onlineUsers = {};

if (process.env.NODE_ENV === 'production') {
  //set static folder
  app.use(express.static('client/build'));
}
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});

mongoose
  .connect(process.env.MONGO_URI, { useNewUrlParser: true })
  .then(res => {
    const expressServer = app.listen(process.env.PORT || 8000);
    console.log('listening on port 8000');

    // BEGIN SOCKET IO:
    const io = socketio(expressServer);
    io.on('connection', socket => {
      console.log('online users: ', onlineUsers, 'new user: ', socket.id);
      const setUpCurrentChatUser = async () => {
        const token = socket.handshake.query.token;
        if (!token) {
          console.log('no token auth denied');
        } else {
          try {
            const decoded = jwt.verify(token, process.env.SECRET);
            // console.log('DECODED: ', decoded);
            let current_time = Date.now() / 1000;
            if (decoded.exp < current_time) {
              console.log('expired');

              // token is expired, not authorized
            } else {
              let decodedUser = await User.findOne({
                _id: decoded.tokenUser.userId
              });
              const currentUser = {
                userId: decodedUser._id,
                socketId: socket.id
              };
              onlineUsers = addUser(onlineUsers, currentUser);

              const currentUserFriendList = decodedUser.friendList;

              const modifiedFriendList = currentUserFriendList.map(friend => {
                if (friend in onlineUsers) {
                  const newFriend = {
                    friendId: friend,
                    isOnline: true,
                    socketId: onlineUsers[friend].socketId
                  };
                  return newFriend;
                } else if (!(friend in onlineUsers)) {
                  const newFriend = {
                    friendId: friend,
                    isOnline: false,
                    socketId: null
                  };
                  return newFriend;
                }
              });

              socket.emit('friendList', modifiedFriendList);
            }
          } catch (error) {
            console.log('jwt error ');
          }
        }
      };

      setUpCurrentChatUser();

      const addUser = (userList, user) => {
        let newList = Object.assign({}, userList);
        newList[user.userId] = user;
        return newList;
      };

      socket.on('newPrivateMessageFromClient', async message => {
        console.log('newPrivateMessageFromClient: ', message);

        const friendId = message.currentFriend.friendId;
        const friendSocketId = onlineUsers[friendId].socketId;

        const newPrivateMessage = new PrivateMessage({
          sender: message.senderId,
          recipient: message.currentFriend.friendId,
          participants: [message.senderId, message.currentFriend.friendId],
          content: message.message
        });
        newPrivateMessage.save().then(result => {
          console.log('newPrivateMessage: ', result);

          //to friend
          io.to(`${friendSocketId}`).emit('privateMessageFromServer', result);

          //to sender
          const userSocketId = onlineUsers[message.senderId].socketId;
          console.log('USER SOCKET ID: ', userSocketId);
          io.to(`${userSocketId}`).emit('ownPrivateMessageFromServer', result);
        });
      });

      socket.on('updateFriendList', async friendList => {
        const modifiedFriendList = friendList.map(friend => {
          if (friend in onlineUsers) {
            const newFriend = {
              friendId: friend,
              isOnline: true,
              socketId: onlineUsers[friend].socketId
            };
            return newFriend;
          } else if (!(friend in onlineUsers)) {
            const newFriend = {
              friendId: friend,
              isOnline: false,
              socketId: null
            };
            return newFriend;
          }
        });

        socket.emit('friendList', modifiedFriendList);
      });

      socket.on('disconnect', async socketId => {
        try {
          const token = socket.handshake.query.token;
          const decoded = jwt.verify(token, 'speakfriendandenter');
          const userId = decoded.tokenUser.userId;
          console.log(
            'DISCONNECT, socket id: ',
            socketId,
            'decoded.tokenUser.userId: ',
            decoded.tokenUser.userId
          );
          delete onlineUsers[userId];
          console.log('updated online users after disconnect: ', onlineUsers);
        } catch (err) {
          console.log(err);
        }
      });
    });
  })
  .catch(err => console.log(err));

这是我的后端文件夹/根文件夹中的package.json:

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "client-install": "npm install --prefix client",
    "start": "node server.js",
    "server": "nodemon server.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix"
  },
  "engines": {
    "node": "10.15.3",
    "npm": "6.9.0"
  },
  "author": "Thomas",
  "license": "MIT",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "crypto": "^1.0.1",
    "dotenv": "^8.1.0",
    "express": "^4.17.1",
    "express-session": "^1.16.2",
    "express-validator": "^6.2.0",
    "gridfs-stream": "^1.1.1",
    "jsonwebtoken": "^8.5.1",
    "method-override": "^3.0.0",
    "mongoose": "^5.6.11",
    "multer": "^1.4.2",
    "multer-gridfs-storage": "^3.3.0",
    "node": "^12.9.0",
    "socket.io": "^2.3.0"
  },
  "devDependencies": {
    "concurrently": "^5.0.0",
    "nodemon": "^1.19.1"
  }
}

1 个答案:

答案 0 :(得分:0)

将其更改回index.js,然后尝试以下操作:

app.get('*', (request, response) => {

response.sendFile(path.join(__dirname, 'client/build', 'index.html'));

 });

});