【问题标题】:React build for static server gives 404 error静态服务器的 React 构建给出 404 错误
【发布时间】:2020-05-22 22:08:24
【问题描述】:

我有一个React 应用程序,它在本地运行良好,但是当我尝试在静态Node 服务器serve (npm serve) 上使用

serve -s build

服务器返回一个404 The requested path could not be found 页面。我的理解是这个问题与我在应用程序中使用BrowserRouter 的事实有关。我用下面的代码在根目录下放了一个.htaccess文件,但没有解决问题。

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]

</IfModule>

我看到了一个关于 Node 环境的建议,但我不明白将代码放在哪里。

app.get('*', function (req, res) {
  res.send('index_path')
})

我的 index.js 文件如下。

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { Route, Switch, BrowserRouter as Router } from 'react-router-dom';
import App from './App';
import Service from './javascript/Service';
import { PageNotFound } from './PageNotFound';
import * as serviceWorker from './serviceWorker';

const routing = (
    <Router>
        <Switch>
            <Route exact path="/" component={App} />
            <Route path="/Service/:serviceName" component={Service} />
            <Route component={PageNotFound} />
        </Switch>
    </Router>    
);

ReactDOM.render(routing, document.getElementById('root'));

serviceWorker.unregister();

【问题讨论】:

    标签: node.js reactjs serve


    【解决方案1】:

    你应该首先构建你的项目

    npm run build (or yarn)
    

    下次安装serve

    npm install -g serve
    

    然后运行这段代码

    serve -s build
    

    【讨论】:

      猜你喜欢
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      相关资源
      最近更新 更多