![](/img/trans.png)
[英]How do I go to different paths on my react website without getting "Cannot GET /path"?
[英]Can I host the same react app at two different paths on my website?
我目前的設置
為此,我在 package.json 中設置了
"homepage": "https://example.com/register/"
在我的 App.js 上
<Router history={history} basename="/register">
</Router>
我的 NGINX 看起來像這樣:
server {
listen 5400;
access_log /var/log/nginx/wordpress-access.log;
error_log /var/log/nginx/wordpress-error.log;
location / {
root /home/ubuntu/...../build/;
index index.html;
expires 1d;
try_files $uri /index.html;
}
}
server {
listen 443 ssl;
listen [::]:443;
index index.php index.html index.htm;
server_name example.com;
location / {
... old setup
}
location /register {
proxy_pass http://127.0.1.1:5400/;
}
}
這是我想要做的。 我想在 url example.com/pricing
上托管相同的 react 應用程序。
我怎樣才能做到這一點? 我希望代碼/邏輯等的重復最少。
一種解決方案是進行兩個單獨的構建,一個用於/register
,另一個用於/pricing
。
您可以使用環境變量PUBLIC_URL
代替您的package.json
的homepage
字段來指定根,並添加一個名為REACT_APP_BASENAME
的自定義環境變量,您將其用於Router
的basename
REACT_APP_BASENAME
。
<Router history={history} basename={process.env.REACT_APP_BASENAME}>
您的構建腳本可能如下所示:
"build:register": "PUBLIC_URL=https://example.com/register/ REACT_APP_BASENAME=/register node scripts/build.js",
"build:pricing": "PUBLIC_URL=https://example.com/pricing/ REACT_APP_BASENAME=/pricing node scripts/build.js"
這可能不適用於您的特定設置,但 react-router v5 有一個新功能,允許同一組件有多個匹配器:
// Instead of this:
<Switch>
<Route path="/users/:id" component={User} />
<Route path="/profile/:id" component={User} />
</Switch>
// you can now do this:
<Route path={["/users/:id", "/profile/:id"]} component={User} />
https://reacttraining.com/blog/react-router-v5/#new-features
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.