访问 golang net/http 其他路由时返回 404 错误
时间:2024-03-07
浏览:378
作者:佚名
从现在开始,我们要努力学习啦!今天我给大家带来《访问 golang net/http 其他路由时返回 404 错误》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!
问题内容
我有一个 web 应用程序,它以 react 作为前端,以 golang 作为后端。
我的想法是使用 http.handle 来提供 react router 的路径,然后渲染正确的组件。
问题是,当我尝试连接到 localhost:8080 时,一切顺利,但是当我尝试连接到 localhost:8080/example 时,它给我 404 页面未找到
为了服务我的反应应用程序,我使用以下代码:
package main
import (
"net/http"
"log"
)
// frontend public path
const public = "../frontend/public/";
func main(){
// route handling
http.handle("/", http.fileserver(http.dir(public)));
http.handle("/example", http.fileserver(http.dir(public)));
log.println("listening on http://locahost:8080");
log.fatal(http.listenandserve(":8080", nil));
}
我的直路由器:
import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import Home from '../pages/Home/Home';
import Admin from '../pages/Example/Example';
export default class RouteHandler extends React.Component{
render(){
return(
<Router>
<Switch>
<Route exact path='/'>
<Home />
</Route>
<Route exact path='/example'>
<Admin />
</Route>
</Switch>
</Router>
)
}
}
解决方案
我找到了一个解决方案,问题是 http.handle("/example", http.fileserver(http.dir(public))); golang 试图找到路径 ../frontend/public/示例。
为了解决这个问题,我使用了 http.stripprefix:
package main
import (
"net/http"
"log"
)
// frontend public path
const public = "../frontend/public/";
func main(){
// route handling
http.Handle("/", http.FileServer(http.Dir(public)));
http.Handle("/admin/", http.StripPrefix("/admin/", http.FileServer(http.Dir(public))));
log.Println("Listening on http://locahost:8080");
log.Fatal(http.ListenAndServe(":8080", nil));
}
以上就是《访问 golang net/http 其他路由时返回 404 错误》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
热门专题
