登录
首页 >  Golang >  Go问答

我无法让 golang 识别我的带有参数的 get 请求

来源:stackoverflow

时间:2024-03-25 10:54:30 235浏览 收藏

在使用 React 的 axios 创建带参数的 GET 请求时,遇到了 404 错误。问题在于服务器端的 Gorilla/Mux 路由器未正确注册,导致无法识别带参数的请求。解决方法是使用 Mux 路由器注册所有处理程序,并将其作为第二个参数传递给 ListenAndServe 函数。

问题内容

我正在尝试使用 react 中的参数创建一个简单的 axios get 请求,以便与 go 一起使用。无论我做什么,都会不断收到 get url 路径未找到 (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(
            
specific location
) } } 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 函数,因为找不到我的获取请求。我应该怎么做才能从我的 get 请求中获取参数?


解决方案


您尚未使用您的多路复用器路由器。由于您将 nil 传递给 listenandserve,因此它使用默认路由器,该路由器附加了所有其他处理程序。相反,请使用 mux 路由器注册所有处理程序,然后将其作为第二个参数传递给 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)
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《我无法让 golang 识别我的带有参数的 get 请求》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>