2017-06-03 39 views
2

我想创建一个快速应用程序,可以在前端使用React和React-router。所以我正在加载index.html文件并让反应路由器处理路由的其余部分。但是当刷新页面时,如果没有快速路由的反应路由器url,我显然会收到{can not GET .....}消息。所以我在所有路线之后添加了一条后备路线,以便在没有路线时始终返回index.html。我现在有路由到“/ api/...”,“/”和“*”,我也提供来自“/ public/build”和“/ app/src/static /”的静态文件。 。当调用“/”时,一切都很好,当调用“*”时index.html被加载,但index.js和styles.css文件都加载了index.html中的内容。因此,我的浏览器获得了一个styles.css文件,其中包含一堆html,而使用“/”路径时,.js和.css文件可以正确加载。快递回退路线也用于静态文件

因此,导航到“/”会正确加载所有静态文件的索引页。然后,我可以使用我的react-router-dom NavLink导航到不同视图,而无需向服务器发送请求。但是当我尝试直接加载任何反应路由器-DOM页面获取我的index.html,但我的index.js具有相同内容的index.html,同为styles.css的

我的代码:

const app = express(); 

app.use(bodyParser.urlencoded({ extended: true})); 
app.use(bodyParser.json()); 

passportConfig(passport); 
app.use(passport.initialize()); 
app.use(passport.session()); 

app.use('/api/user', userRoutes); 
app.use('/api', championRoutes); 

app.use('/public/build', express.static(__dirname + '/public/ReactApp/build')); 
app.use("/app/src/static/image", express.static(__dirname + '/public/ReactApp/src/static/image')); 
app.use("/app/src/static/style", express.static(__dirname + '/public/ReactApp/src/static/style')); 

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

app.get('*', (req, res) => { 
    res.sendFile(path.resolve(__dirname, '..', 'index.html')); 
}); 

app.listen(8080,() => { 
    console.log('started on port 8080'); 
}); 

userRoutes和championRoutes变量都包含一个有几个路由集的express.Router对象。

编辑:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Page Title</title> 
     <link href="app/src/static/style/styles.css" rel="stylesheet" /> 
     <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> 
    </head> 
    <body> 
     <div id="app"></div> 

     <script 
       src="https://code.jquery.com/jquery-3.2.1.min.js" 
       integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" 
       crossorigin="anonymous"></script> 
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
     <script src="public/build/index.js"></script> 
    </body> 
</html> 
+0

你可以发布你如何纳入'index.html'了'index.js'文件? – squgeim

+0

@squgeim当然看到完整的HTML页面的编辑 –

回答

1
<script src="public/build/index.js"></script> 

这意味着该位置是相对于当前路径,也就是说,如果你在http://somedomain.com/page2,则路径index.jshttp://somedomain.com/page2/public/build/index.js(在你的案例将服务于index.html文件)。

要指定网址的基础相对路径相反,先从路径/

<script src="/public/build/index.js"></script> 
+0

哇不能相信我犯了这样一个愚蠢的错误。谢谢 –