Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

reactjs - Deployment problems with React-Express App

I'm trying to deploy a MERN app (built with create react app) to Heroku, but whenever I try to access the URL, it returns with a 404 error.

During development I structured my project so that it runs on two different servers: client side on local host:3000, which proxies requests to express (at localhost:5000).

I've run npm run build, set up static middleware, and tried to configure my api calls/routes correctly, but it still isn't working. Any suggestions as to why, and how I can fix it? Details as follows:

Project Structure

+client
   |
   +-build
      +-static
        +-css
        +-js
        +-media
   +-node_modules
   +-public
   +-src
     |
     +-components
        +-App.js
        +-index.js
//server
+-models
+-node-modules
+-package-lock.json
+-package.json
+-server.js

Proxy (in package.json):
"proxy": "http://localhost:5000"

Server config:

const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));


//Middleware
if (process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, '../client/build')));
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded())
app.use(cors())

Here's how I;ve structured my APIs. Note: I've removed the 'localhost:5000' from the URL of my axios requests:

API call from React component:

    useEffect(() => {
    axios.get('/api/all-reviews')
    .then(review => {
        setReviews(review.data)
    })
    .catch(err => {
        console.log(err)
    })
},[])

Corresponding express route

app.get('/api/all-reviews', (req,res) => {
    Review.find()
    .then((result) => {
        res.send(result)
    })
    .catch(err => {
        console.log(err)
    })
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...