404 Not Found nginx React

时间:2017-11-20 10:14:44

标签: reactjs nginx heroku react-router

我有一个反应应用程序,我使用快递服务。它在本地运行良好,但当我将它部署到heroku时,我收到此错误404 Not Found。

错误是当我打开例如此链接独立于单独的浏览器窗口时:

http://localhost:9000/projects/5a0df094c27078039346fee2

效果很好。但是如果我部署到heroku然后我尝试相同的调用我得到404。 如果我在内部导航我不会得到404,但只有当我在浏览器中的一个单独的窗口打开它并且它是heroku时才会发生这种情况。 http://www.mywebsite.website/projects/5a0df05dc27078039346fedf

在我的快递服务器中,我有这段代码:

// server/app.js
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();

// Setup logger
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));

// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));

app.get('/projects/:ProjectId', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));

});

app.get('/projects/', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));

});
// Always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});


app.use(function(req, res, next){
  res.status(404);

  // respond with html page
  if (req.accepts('html')) {
    res.render('404', { url: req.url });
    return;
  }

  // respond with json
  if (req.accepts('json')) {
    res.send({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});
module.exports = app;

对于我的反应应用程序,我有这个代码。

<Switch>
    <AppliedRoute path="/" exact component={AsyncHome} props={childProps} />
    <AppliedRoute
      path="/projects/:ProjectId"
      exact
      component={AsyncSingleProject}
      props={childProps}
    />
    {/* Finally, catch all unmatched routes */}
    <Route component={AsyncNotFound} />
  </Switch>

1 个答案:

答案 0 :(得分:1)

不知道在heroku中的部署,但我尝试在公共IP中部署并遇到同样的问题,我认为这是因为路由在localhost中正常工作但在使用nginx部署期间无法正常工作。

我已经编辑了&#34;默认&#34;我的机器nginx / 1.4.6(Ubuntu)中/ etc / nginx / sites-available / default中的文件

sudo gedit /etc/nginx/sites-available/default

在服务器内部,您可以找到位置,编辑该位置并更改为

server{
.......
location / {
try_files $uri /index.html;
} 
........
}

简单。这对我有用。希望这会对某人有所帮助。 感谢

相关问题