как сделать так, чтобы моя ссылка на герою работала после входа в систему? - PullRequest
0 голосов
/ 14 апреля 2019

Я развернул свое приложение MERN в Heroku, но после входа по ссылке, полученной от Heroku, страница не отображается. Похоже, что Heroku не подключается к моему MongoDB или, возможно, есть другие проблемы. Пожалуйста, помогите?

Ниже мой код в app.js:

const express = require("express");
const app = express();
const bodyParser = require('body-parser');
// const cors = require('cors');`enter code here`
require('./models/db');
const Task = require('./models/task.model');
const mongoose = require("mongoose");
const taskRoutes = express.Router();
const path = require('path');
require("dotenv").config();
 //const routes = require("./routes");
// const taskController = require('./controllers/taskController');

//app.use(cors());
if (process.env.NODE_ENV === 'production') {
  // Exprees will serve up production assets
  app.use(express.static(path.join(__dirname, 'client/build')));

  // Express serve up index.html file if it doesn't recognize route
  app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
  });
}

// app.use('/task', taskController);
app.use(bodyParser.json());
//app.use(express.static(path.join(__dirname, 'public')))
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost:27017/TaskDB";
require("dotenv").config(); 


// connection.once('open', function() {
//     console.log("MongoDB database connection established successfully");
// })

taskRoutes.route('/').get(function(req, res) {
  Task.find({})
    .then((results) => {
        // console.log('here', results)
        res.send(results);
    })
});

taskRoutes.route('/:id').get(function(req, res) {
  let id = req.params.id;
  Task.findById(id, function(err, task) {
      res.json(task);
  });
});

taskRoutes.route('/update/:id').post(function(req, res) {
  Task.findById(req.params.id, function(err, task) {
      if (!task)
          res.status(404).send("data is not found");
      else
          task.Done = req.body.Done;
          task.DueDate = req.body.DueDate;
          task.TaskName = req.body.TaskName;
          task.PerformBy = req.body.PerformBy;
          task.Odom = req.body.Odom;
          task.CCAK = req.body.CCAK;
          task.CCBHI = req.body.CCBHI;
          task.SGWS = req.body.SGWS;
          task.NWB = req.body.NWB;
          task.Quarterly = req.body.Quarterly;
          task.Note = req.body.Note;
          task.save().then(task => {
              res.json('Task updated!');
          })
          .catch(err => {
              res.status(400).send("Update not possible");
          });
  });
});

taskRoutes.route('/add').post(function(req, res) {
    console.log(req.body);
  let task = new Task(req.body);
  task.save()
      .then(task => {
          console.log("task is successly save");
          res.status(200).json({'task': 'task added successfully'});
      })
      .catch(err => {
          console.log("something goes wrong!");
          res.status(400).send('adding new task failed');
      });
});

 taskRoutes.route('/save/:id').put(function(req, res){
         console.log('in route',req.body);
         Task.findOneAndUpdate({ _id: req.params.id }, req.body)
            .then(res => console.log(res))
            .catch(err => res.status(422).json(err));
     });

  taskRoutes.route('/delete/:id').delete(function(req, res){
        console.log(req.body);

        Task.findOneAndRemove({ _id: req.params.id }, req.body)
        .then(res => console.log(res))
        .catch(err => res.status(422).json(err));
    });

  taskRoutes.route('/undo').put(function(req, res){
        console.log(req.body);

        Task.updateMany({Done: true}, {Done: false})
        .then(res => console.log(res))
        .catch(err => res.status(422).json(err));
    });



app.use('/Tasks', taskRoutes);

mongoose.Promise = Promise; 
mongoose.connect(MONGODB_URI, function(err){
  if (err) throw err;
  console.log("connected to MongoDB");
});

const port = process.env.PORT || 3002;

// Start the API server
app.listen(port, () =>
  console.log(`?  ==> Epress Server now listening on PORT ${port}!`)
);

Ниже мой код в package.json из app.js:

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "body-parser": "^1.18.3",
    "concurrently": "^4.1.0",
    "cookie-parser": "~1.4.3",
    "cors": "^2.8.5",
    "debug": "~2.6.9",
    "dotenv": "^7.0.0",
    "express": "~4.16.0",
    "http-errors": "~1.6.2",
    "mongod": "^2.0.0",
    "mongoose": "^5.3.4",
    "morgan": "~1.9.0",
    "nodemon": "^1.18.10",
    "path": "^0.12.7",
    "pug": "2.0.0-beta11"
  },
  "scripts": {
    "heroku-postbuild": "cd client && npm install --only=dev && npm install && npm run build",
    "start": "node app.js",
    "client": "cd client && npm run start",
    "install": "cd client && npm install",
    "build": "cd client && npm run build",
    "dev": "concurrently \"node app.js\" \"cd client && npm start \""
  },
  "engines": {
    "node": "8.9.2"
}
}

Ниже App.js:

import React, { Component } from 'react';
import './App.css';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import fire from './config/Fire';
import TaskList from './components/Task';
import EditTask from './components/EditTask';
import CreateTask from './components/CreateTask';
import Login from './components/Login';
import Navbar from './components/Navbar';
import Home from './components/Home';
import Error from './components/Error';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user: {},
    };
    this.authListener = this.authListener.bind(this);
  }

  componentDidMount() {
    this.authListener();
  }

  authListener() {
    fire.auth().onAuthStateChanged((user) => {
      //console.log(user);
      if (user) {
        this.setState({ user });
       // localStorage.setItem('user', user.uid);
      } else {
        this.setState({ user: null });
       // localStorage.removeItem('user');
      }
    });
  }

  render() {
    return (
    <BrowserRouter className="App">
     <Navbar />
     <Switch>
     <Route path="/" component={Home} exact/> 
     <Route path="/edit/:id" component={EditTask} />
     <Route path="/create" component={CreateTask} />

     <div>
     {this.state.user ?  
           ( <TaskList/>) : (<Route path="/login" component={Login} exact/>)}
     </div>

     <Route component={Error}/>

     </Switch>  

     </BrowserRouter>

     )
}
}
   export default App;

Пожалуйста, дайте мне знать, если вам нужно увидеть больше?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...