我有一个简单的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;
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;
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;
const api = process.env.BACKEND_URL || 'http://localhost:5000'
export const getUsers = () => (
fetch(`${api}/api/users`)
.then(res => res.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上运行的用户页面
答案 0 :(得分:1)
您正在提供静态文件,但您还需要将所有HTTP GET请求转发到客户端响应路由器,以便它可以处理。您可能希望将此路线添加到app.js
:
app.get("*", function (req, res) {
res.sendFile(__dirname + "/path/to/index.html")
})