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

标签 javascript reactjs go

我有一个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/

相关文章:

javascript - DeviantArt 的脚本负责发送个人资料评论

Javascript/JQuery 使用 div 调整文本区域大小/"grippie"

javascript - 具有相同按钮的 onClick 操作和功能

go - 如何使用文件作为正文复制 cURL 命令

compiler-construction - 如何为 Go 构建 8g 和 6g Go 编译器

javascript - 为什么后面更新数据时v-if不受影响?

javascript - 如何在 Angular 1.X 和 Angular Material 中重置具有必填字段的表单

reactjs - React Native 评估 this.state 中的表达式

javascript - 有关如何以及何时在 React 中使用焦点的示例

python - Go - 我如何在 go 代码中执行此 python 代码?