2017-12-18 102 views
0

我使用webpack dev服務器來運行本地Web服務器。Webapck服務器的路由無法獲取/ page

當我使用瀏覽器輸入網址/localhost:8080/sign_in,我得到了錯誤。

無法獲取/ sign_in

我在webpack.config.js添加對象historyApiFallback: true,並得到解決。

devServer: { 
    inline: true, 
    port: 8080, 
    historyApiFallback: true, 
    headers:{ 
     'Access-Control-Allow-Origin': '*', 
     "Access-Control-Allow-Methods": "POST, GET, OPTIONS" 
    } 
    } 

但是,當我編譯webpack -p和運行node server.js再次發生同樣的錯誤。

其次server.js代碼

const express = require('express'); 
const path = require('path'); 
const port = process.env.PORT || 8080; 
const app = express(); 
const history = require('connect-history-api-fallback'); 

const indexPath = path.join(__dirname, './public/index.html') 
const publicPath = express.static(path.join(__dirname, '/public')) 

app.use(publicPath) 
app.use(history()) 

app.get('/', (req, res) => { 
    res.sendFile(path.resolve(indexPath)); 
}); 



app.listen(port); 

我怎麼固定呢?

+0

你只定義了路徑'/'。你也需要添加'/ sign_in'。 – Seblor

+0

@Seblor我在我的應用程序中使用了react-routes,所以每個頁面都依賴於/index.html –

回答

1

您尚未定義登錄路線。

app.get('/sign-in', (req, res) => { 
    res.sendFile(path.resolve( PATH )); 
}); 

由於服務器端渲染不活動,您不能直接登錄。你必須去索引並點擊鏈接,這樣react-router才能到達那條路徑

+0

我如何設置所有路由依賴於'index.html'就像rails setted routes'get'* path'一樣: 「回家#index''? –

+1

''app.get('/ *',(req,res)=> { res.sendFile(path.resolve(indexPath)); });' 這將使所有的路由去索引 – illiteratewriter

+0

謝謝兄弟, 有用! –