简体   繁体   English

Node(Express)/ React应用仅在本地工作

[英]Node (Express) / React app only works locally

Issue Outline 发行大纲

I have a simple Node / React app, which runs fine using heroku local . 我有一个简单的Node / React应用程序,使用heroku local可以正常运行。

The Node backend has an /api/users endpoint, which returns some hardcoded JSON. Node后端有一个/api/users端点,该端点返回一些硬编码的JSON。

After heroku local , visiting localhost:5000/users works as expected, displaying the hardcoded users as per the Users.js React component. heroku local ,访问localhost:5000/users将按预期工作,并根据Users.js React组件显示硬编码用户。

However, when pushed to Heroku, only the / root page works. 但是,当推送到Heroku时,仅/根页面有效。 Going to /users shows Not Found , and going to /api/users returns the JSON. 转到/users显示Not Found ,转到/api/users将返回JSON。

I'm not sure why it works locally and not on Heroku, any help is appreciated. 我不确定为什么它可以在本地而不是在Heroku上运行,因此不胜感激。

Code

Express routes: 快速路线:

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;

The Express app.js file: 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 file: 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 file: 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 反应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"
}

Screenshots 截图

Home page running locally 主页在本地运行 在本地运行的主页

Home page running on Heroku 在Heroku上运行的主页 在heroku上运行的主页

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

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

You are serving static files but you also need to forward all HTTP GET requests to client side react router so it can handle. 您正在提供静态文件,但还需要将所有HTTP GET请求转发到客户端react路由器,以便它可以处理。 You may want to put this route to your app.js : 您可能希望将此路由放入您的app.js

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Heroku上使用快速应用程序崩溃的Node.js在本地工作 - Node.js with express app crashes on Heroku, works locally Express React应用程序可在本地运行,但在部署Heroku时出错 - Express React app works locally but gives error on heroku deploy React Express Routing在本地工作,但不适用于Heroku - React Express Routing works locally but not on Heroku Netlify/React 前端未连接到 Node.js/Express/MongoDB Atlas/Heroku 后端,但在开发/本地工作 - Netlify / React front end not connecting to Node.js / Express / MongoDB Atlas / Heroku backend but works in development/locally Heroku Node.js(express.js)应用程序在本地运行,但在使用MongoDB时在heroku上失败 - Heroku Node.js (express.js) App Works Locally but failed on heroku when using MongoDB Node/React 应用程序在本地运行良好,但在 Internet 上出现 502 错误 - Node/React app works fine locally but getting 502 error over the internet express.static()仅在本地运行时有效 - express.static() only works when run locally Plesk Obsidian、IISNode 和 Express 问题 - 应用程序只能在本地运行 - Plesk Obsidian, IISNode and Express problem - application only works locally Node.js Express应用程序只能通过本地主机运行,不能通过网络运行(找不到文件或目录)? - Node.js Express app only works via localhost, does not work over network (File or Directory not found)? Node.js/Express.js 应用程序仅适用于端口 3000 - Node.js/Express.js App Only Works on Port 3000
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM