首页 > 解决方案 > 我无法让 golang 识别带有参数的 get 请求

问题描述

我正在尝试使用 React 中的参数创建一个简单的 axios get 请求以与 Go 一起使用。无论我做什么,都会不断收到 GET URL path not found (404) 错误。这是JS

import React, {Component} from 'react'
import axios from "axios"

class ShowLoc extends Component {
    constructor(props){
        super(props)
    }

    componentDidMount(){
        const {id} = this.props.match.params
        axios.get(`/loc/${id}`)
    }

    render() {
        return(
            <div>
                Specific Location
            </div>
        )
    }
}

export default ShowLoc

这是我的 server.go 文件的相关部分。我正在使用 gorilla/mux 来识别参数

func main() {

    fs := http.FileServer(http.Dir("static"))
    http.Handle("/", fs)

    bs := http.FileServer(http.Dir("public"))
    http.Handle("/public/", http.StripPrefix("/public/", bs))

    http.HandleFunc("/show", show)
    http.HandleFunc("/db", getDB)

    r := mux.NewRouter()
    r.HandleFunc("/loc/{id}", getLoc)

    log.Println("Listening 3000")
    if err := http.ListenAndServe(":3000", nil); err != nil {
        panic(err)
    }
}

func getLoc(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
        return
    }
    id := r
    fmt.Println("URL")
    fmt.Println(id)
}

因为找不到我的获取请求,所以我从未点击过我的 getLoc 函数。我应该如何从我的获取请求中获取参数?

标签: javascriptreactjsgo

解决方案


你还没有使用你的多路复用路由器。由于您传递nilListenAndServe,它使用的是默认路由器,该路由器附加了所有其他处理程序。相反,将所有处理程序注册到您的多路复用路由器,然后将其作为第二个参数传递给ListenAndServe.

func main() {
    r := mux.NewRouter()

    fs := http.FileServer(http.Dir("static"))
    r.Handle("/", fs)

    bs := http.FileServer(http.Dir("public"))
    r.Handle("/public/", http.StripPrefix("/public/", bs))

    r.HandleFunc("/show", show)
    r.HandleFunc("/db", getDB)

    r.HandleFunc("/loc/{id}", getLoc)

    log.Println("Listening 3000")
    if err := http.ListenAndServe(":3000", r); err != nil {
        panic(err)
    }
}

func getLoc(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
        return
    }

    id := r
    fmt.Println("URL")
    fmt.Println(id)
}

推荐阅读