簡體   English   中英

將mern應用程序部署到heroku后路由問題

[英]problem with routing after deploying mern app to heroku

我制作了一個運動跟蹤器 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或任何其他平台,就沒有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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM