节点(快速)/ React应用程序仅在本地运行

时间:2017-08-30 22:32:40

标签: node.js reactjs express heroku

问题大纲

我有一个简单的Node / React应用程序,使用heroku local可以正常运行。

Node后端有一个/api/users端点,返回一些硬编码的JSON。

heroku local之后,访问localhost:5000/users按预期工作,根据Users.js React组件显示硬编码用户。

但是,当推送到Heroku时,只有/根页面有效。转到/users会显示Not Found,然后转到/api/users会返回JSON。

我不确定为什么它在本地运行而不是在Heroku上,任何帮助都表示赞赏。

代码

快递路线:

var express = require('express');
var router = express.Router();
var path = require('path');

router.get('/api/users', function(req, res, next) {

  res.json([{id: 1, name: 'Colin'}, {id: 2, name: 'Spodie'}])
});

module.exports = router;

Express app.js文件:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cors = require('cors');

var config = require('./config/dev')
var index = require('./routes/index');

var app = express();
app.use(cors())

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// serve static files from React 
app.use(express.static(path.join(__dirname, '../frontend/build')));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

React App.js文件:

import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom';
import Users from './Users';
import NotFound from './NotFound';
import Home from './Home';

class App extends Component {
  state = {users : []}

  render() {
    return (
      <div>
        <Switch>
        <Route exact path='/' component={Home}/>
        <Route exact path='/users' component={Users}/>
        <Route component={NotFound} />
        </Switch>
      </div>
    );
  }
}

export default App;

React api.js文件:

const api = process.env.BACKEND_URL || 'http://localhost:5000'

export const getUsers = () => (
  fetch(`${api}/api/users`)
    .then(res => res.json())
)

React package.json

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-router-dom": "^4.2.2",
    "react-scripts": "1.0.12"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:5000"
}

截图

本地运行主页 home page running locally

在Heroku上运行主页 home page running on heroku

本地运行的用户页面 users page running locally

在Heroku上运行的用户页面 users page running on heroku

1 个答案:

答案 0 :(得分:1)

您正在提供静态文件,但您还需要将所有HTTP GET请求转发到客户端响应路由器,以便它可以处理。您可能希望将此路线添加到app.js

app.get("*", function (req, res) {
    res.sendFile(__dirname + "/path/to/index.html")
})