gpt4 book ai didi

javascript - 当尝试调用不是/的其他路由时,golang net/http会给出404错误

转载 作者:行者123 更新时间:2023-12-01 22:24:11 24 4
gpt4 key购买 nike

我有一个Web应用程序,其中有React作为前端,而Golang作为后端。
我的想法是使用http.handle提供服务到React Router的路径,然后渲染正确的组件。

问题是,当我尝试连接到localhost:8080时,一切顺利,但是当我尝试连接到localhost:8080/example时,给了我404 page not found
为了提供我的应用程序,我使用以下代码:

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/example

为了解决这个问题,我使用了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));
}

关于javascript - 当尝试调用不是/的其他路由时,golang net/http会给出404错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61084976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com