Express Server Post API在Heroku上不起作用,但在本地服务器上起作用

时间:2020-02-20 03:53:20

标签: javascript reactjs express heroku

我希望你们做得很好 我用express js制作了一个Web服务器,并且在我的本地服务器上工作正常。 实际上,我不是从头开始制作的,而是从“ https://github.com/jm-shi/MERN-Social-Network”中拉出来的 并根据我的需要改变一些东西。 然后我将其部署在heroku上,现在无法正常工作。 它显示主页,但没有任何api起作用,无论是获取还是发布。

const bodyParser = require('body-parser');
const express = require('express');
const logger = require('morgan');
const mongoose = require('mongoose');
const path = require('path');
const posts = require('./routes/postRoute');
const users = require('./routes/userRoute');
const dbURI = process.env.REACT_APP_DB_URI || require('./secrets').dbURI;

const app = express();
const port = process.env.PORT || 5000;

// Enable CORS
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
 'Access-Control-Allow-Headers',
 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, PATCH, DELETE');
return res.status(200).json({});
}
return next();
});

mongoose
  .connect(dbURI, {
   useNewUrlParser: true,
   useUnifiedTopology: true,
   useCreateIndex: true
  })
 .then(() => console.log('Connected to MongoDB'))
 .catch(err => console.log('Failed to connect to MongoDB', err));

 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({ extended: true }));
 app.use(logger('dev'));
 app.use('/posts', posts);
 app.use('/users', users);
 // app.use(express.static(path.resolve(__dirname, '.', 'client', 'build')));
 // if (process.env.NODE_ENV === 'production') {
 //   app.get('*', (req, res) => {
 //     res.sendFile(path.resolve(__dirname, '.', 'client', 'build', 'index.html'));
 //   });
 // }
 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'));
 });
 app.listen(port, () => {
  console.log(`Started up at port ${port}`);
 });

这是发布路线

    const express = require('express');
    // const { ObjectID } = require('mongodb');
    const Post = require('../models/postModel');

    const router = new express.Router();

    router.get('/memories', async (req, res) => {
      const posts = await Post.find().sort({ timestamp: -1 });
      res.status(200).json(posts);
    });

    router.post('/memories', async (req, res) => {
      const newPost = new Post({
        title: req.body.title,
        body: req.body.body,
        createdAt: new Date().getTime()
      });
      try {
        const post = await newPost.save();
        return res.status(201).json(post);
      } catch (err) {
        return res.status(400).send(err);
      }
    });

    router.post('/update', async (req, res) => {
      Post.findById(req.body._id, (err, obj) => {
        // res.send(obj);
        obj.title = req.body.title;
        obj.body = req.body.body;
        obj.save((error, newObj) => {
          if (error) {
            res.send(error);
          } else {
            res.send(newObj);
          }
        });
      });
    });

    router.delete('/:id', async (req, res) => {
      try {
        const post = await Post.findById(req.params.id);
        await post.remove();
        return res.json({ success: true });
      } catch (err) {
        return res.status(404).send(err);
      }
    });

    module.exports = router;

这是用户路线

    const bcrypt = require('bcrypt');
    const express = require('express');
    const jwt = require('jsonwebtoken');
    const validateLogin = require('../validation/validateLogin');
    const validateSignup = require('../validation/validateSignup');
    const User = require('../models/userModel');

    const router = new express.Router();


    router.get('/logout', (req, res) => {
      delete req.session.authStatus;
      res.send([
        'You are now logged out.',
        '<br/>',
        '<a href="./secure">Return to the secure page. You will have to log in again.</a>'
      ].join(''));
    });

    // Sign up a user
    router.post('/signup', async (req, res) => {
      const { errors, isValid } = validateSignup(req.body);

      if (!isValid) {
        return res.status(400).json(errors);
      }

      try {
        const user = await User.find({ email: req.body.email }).exec();
        if (user.length > 0) {
          return res.status(409).json({ error: 'Email already exists.' });
        }
        return bcrypt.hash(req.body.password, 10, (error, hash) => {
          if (error) {
            return res.status(500).json({ error });
          }
          const newUser = new User({
            firstname: req.body.firstname,
            createdAt: new Date().getTime(),
            email: req.body.email,
            username: req.body.username,
            lastname: req.body.lastname,
            gender: req.body.gender,
            password: hash
          });
          return newUser
            .save()
            .then((result) => {
              res.status(201).json({ user: result._id });
            })
            .catch((err) => {
              res.status(500).json({ error: err });
            });
        });
      } catch (err) {
        return res.status(500).json({ err });
      }
    });

    // Log in a user
    router.post('/login', async (req, res) => {
      const { errors, isValid } = validateLogin(req.body);

      if (!isValid) {
        return res.status(400).json(errors);
      }

      try {
        const user = await User.findOne({ email: req.body.email }).exec();
        if (!user) {
          return res.status(401).json({
            email: 'Could not find email.'
          });
        }

        return bcrypt.compare(req.body.password, user.password, (err, result) => {
          if (err) {
            return res.status(401).json({
              message: 'Auth failed.'
            });
          }
          if (result) {
            const token = jwt.sign(
              {
                avatarColor: user.avatarColor,
                createdAt: user.createdAt,
                name: user.name,
                email: user.email,
                showEmail: user.showEmail,
                userId: user._id
              },
              process.env.REACT_APP_JWT_KEY || require('../secrets').jwtKey,
              {
                expiresIn: '1h'
              }
            );
            return res.status(200).json({
              message: 'Auth successful.',
              token
            });
          }
          return res.status(401).json({
            password: 'Wrong password. Try again.'
          });
        });
      } catch (err) {
        return res.status(500).json({ message: err });
      }
    });

    // Delete a user
    router.delete('/:id', async (req, res) => {
      try {
        await User.remove({ _id: req.params.id }).exec();
        res.status(200).json({ message: 'Successfully deleted user.' });
      } catch (err) {
        res.status(500).json({ message: err });
      }
    });

    module.exports = router;

但仅通过*路线提供构建服务,而其他api均不起作用... 请让我知道服务器本身或其他任何问题...

0 个答案:

没有答案