【问题标题】:404 Not Found nginx React404 未找到 nginx 反应
【发布时间】:2018-05-03 12:43:49
【问题描述】:

我有一个 react 应用程序,我使用 express 提供服务。它在本地运行良好,但是当我将其部署到 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;

对于我的 react 应用,我有这个代码。

<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>

【问题讨论】:

标签: reactjs nginx heroku react-router


【解决方案1】:

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

我已经在我的机器 nginx/1.4.6 (Ubuntu) 中编辑了 /etc/nginx/sites-available/default 中的“默认”文件

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

您可以在服务器中找到位置,对其进行编辑并更改为

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

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

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 2016-06-23
    • 2016-12-27
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多