【问题标题】:problem with routing after deploying mern app to heroku将mern应用程序部署到heroku后出现路由问题
【发布时间】:2019-12-03 23:05:41
【问题描述】:

我制作了一个运动跟踪器 MERN 堆栈应用程序,当我运行 npm start 时,它在我的本地计算机上运行良好(它连接到服务器,我可以添加用户、练习等) 但是当我将它部署到 heroku 时,我可以看到 React 前端,但我无法创建用户、练习等 有谁知道为什么? 我认为这可能是我的一个组件中的 axios 问题,因为我使用 localhost url 而不是 heroku 。但我不知道如何使用heroku 之一。 这是我的创建用户组件:

import React, {Component} from 'react';
import axios from 'axios';

export default class CreateUser extends Component {

    constructor(props) {
        // need to call super() for constructors of subclass in javascript
        super(props);

        // ensure that "this" is referring to the right object
        this.onChangeUsername = this.onChangeUsername.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        // use state to create variables in React
        this.state = {
            username: '',
        }
    }

    onChangeUsername(e) {
        this.setState({
          username: e.target.value
        })
    }

    onSubmit(e) {
        //prevent default HTML behaviour
        e.preventDefault();

        const user = {
          username: this.state.username,
        }

        console.log(user);

        // connect backend to frontend
        // second parameter of axios statement is the body
        // 'user' is from users.js
        axios.post('http://localhost:5000/users/add', user)
            .then(res => console.log(res.data));

        // once the user enters a username, make the username box blank again, staying on the same page
        this.setState({
            username: ''
        })
    }

    render() {
        return (
          <div>
            <h3>Create New User</h3>
            <form onSubmit={this.onSubmit}>
              <div className="form-group"> 
                <label>Username: </label>
                <input  type="text"
                    required
                    className="form-control"
                    value={this.state.username}
                    onChange={this.onChangeUsername}
                    />
              </div>
              <div className="form-group">
                <input type="submit" value="Create User" className="btn btn-primary" />
              </div>
            </form>
          </div>
        )
      }
    }

这是我的 server.js

// tools we need
const express = require('express');
const cors = require('cors');
// mongoose helps connect to mongodb database
const mongoose = require('mongoose');

// setting up server
const app = express();
const port = process.env.PORT || 5000;

const path = require("path")

// cors middeware
app.use(cors());

// helps to parse json
app.use(express.json());

const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');

// whenever go to that url, it will load everything in the second parameter
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);

mongoose.connect(process.env.MONGODB_URI || "mongodb://***:***1@ds227525.mlab.com:27525/heroku_wgczpk05", { 
    //dealing with updates to mongodb
    useNewUrlParser: true, 
    useCreateIndex: true, 
    useUnifiedTopology: true 
}
);

if (process.env.NODE_ENV === 'production') {
    app.use(express.static( 'client/build' ));

    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html')); // relative path
    });
}

//app.use(express.static(path.join(__dirname, "client", "build")))

// starts listening and starts the server
app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
});

请注意,为了这篇文章,我的 mongodb uri 已将我的用户名和密码标为星号。在我自己的文件中,我有我的用户名和密码

【问题讨论】:

  • 在 Heroku 中部署之前,您是否将 MongoDB 中的 IP 列入白名单?

标签: node.js reactjs mongodb heroku mern


【解决方案1】:

问题是一旦应用程序部署到Heroku 或任何其他平台,就没有localhost.localhost 的概念仅存在于您的本地环境中。所以你的 axios 应该向

发送请求
axios.post('/users/add', user)

而不是

axios.post('http://localhost:5000/users/add', user)

因为一切都在一个端口上运行,并且 axios 会自动将路由附加到 URL。

我的意思是,如果您的 heroku 应用程序正在运行 scott.herokuapp.com(示例),

调用该路由后,您的 URL 将是 scott.herokuapp.com/users/add

【讨论】:

  • 即使我删除了 url 的 localhost 部分,我也会收到此错误,但我的 url 中仍然有未定义的部分
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 2014-11-25
  • 2020-05-12
  • 2012-07-08
相关资源
最近更新 更多