Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

reactjs - How to build React app from an apache subfolder?

I have a client with react app. The server is using apache, and he configured the app to be on:

http://my-domain.com/frame

I have build the app and it loads (css+js), but some routing issues still remain. For example, I am using routes, so there are pages like:

http://localhost:3000/frame
http://localhost:3000/page1
http://localhost:3000/page2

It works in my local, and on the server routing works when using the app normally, but when refreshing the page, it "loses" the routing and show error. I mean:

http://my-domain.com/frame
http://my-domain.com/page1
http://my-domain.com/page2

works as long as I am in the app (so frame -> page1 -> page2 works, but going directly to page1 doesn't).

My apache .htacess:

<IfModule mod_rewrite.c>
    RewriteEngine On
        # If an existing asset or directory is requested go to it as it is
        RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
        RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
        RewriteRule ^ - [L]
        # If the requested resource doesn't exist, use index.html
    RewriteRule ^ /index.html
</IfModule>

package.json:

{
...
  "homepage": ".",
...
}

public/manifest.json:

{
...
  "start_url": ".",
...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was using BrowseRouter. I switched to using HashRouter, and it started working.

This is the code:

import {
  HashRouter as Router,
  Switch,
  Route,
} from "react-router-dom";

import Login from './components/Login';
import Queues from './components/Queues';

const App = () => {
    return (
        <div id="app" className="full-height">
            <Router basename={'/'}>
                    <Switch>
                        <Route path='/queues' component={Queues} exact />
                        <Route path='/'  exact >
                            <div className="full-height">
                                <Login />
                            </div>
                        </Route>
                    </Switch>
            </Router>
        </div>
    );      

After build, I copy the build folder to apache where I need it.

Then the url looks like this:

http://localhost:3000/path/to/folder/#/
http://localhost:3000/path/to/folder/#/page1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...