Node(Express)/React应用程序仅在本地工作 [英] Node (Express) / React app only works locally

查看:61
本文介绍了Node(Express)/React应用程序仅在本地工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Node/React应用程序,可以使用heroku local运行良好.

I have a simple Node / React app, which runs fine using heroku local.

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

The Node backend has an /api/users endpoint, which returns some hardcoded JSON.

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

After heroku local, visiting localhost:5000/users works as expected, displaying the hardcoded users as per the Users.js React component.

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

However, when pushed to Heroku, only the / root page works. Going to /users shows Not Found, and going to /api/users returns the JSON.

我不确定为什么它可以在本地而不是在Heroku上运行,因此不胜感激.

I'm not sure why it works locally and not on Heroku, any help is appreciated.

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;

反应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;

反应api.js文件:

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

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

反应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"
}

屏幕截图

本地运行的首页

在Heroku上运行的主页

在本地运行的用户页面

在Heroku上运行的用户页面

推荐答案

您正在提供静态文件,但还需要将所有HTTP GET请求转发到客户端React Router,以便其处理.您可能希望将此路线放置到您的app.js:

You are serving static files but you also need to forward all HTTP GET requests to client side react router so it can handle. You may want to put this route to your app.js:

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

这篇关于Node(Express)/React应用程序仅在本地工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆