简体   繁体   中英

problem with routing after deploying mern app to heroku

I made an exercise tracker MERN stack app and it all works fine in my local computer when I run npm start (it connects to the server, I can add users, exercises, etc) But when I deployed it to heroku, I can see the React frontend but I cannot create users, exercises, etc Does anyone know why? I think it may be a problem with axios in one of my components because I use the localhost url instead of the heroku one. But I do not know how to use the heroku one. Here is my create user component:

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>
        )
      }
    }

Here is my 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}`);
});

Note that my mongodb uri has my username and password starred out for the sake of this post. In my own files, I have my user and password in it

Well the Issue is once app gets deployed to Heroku or any other platform there is no concept of localhost . localhost only exists in your local environment. So you axios should be sending request to

axios.post('/users/add', user)

instead of

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

because everything is running on one port, and axios will automatically append the route to the URL.

What I mean by that is if your heroku app is running on scott.herokuapp.com (example),

Your URL will be scott.herokuapp.com/users/add once that route is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM