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

标签 javascript reactjs go

我正在尝试在 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 函数,因为找不到我的 get 请求。我应该怎么做才能从 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)
}

关于javascript - 我无法让 golang 识别我带参数的 get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51795845/

相关文章:

javascript - 如何在 React 中使用 javascript 模块对象(HTML + JS 嵌入)

testing - golang TestMain() 函数设置测试无法访问的变量

go - go 中的函数和参数解码?

javascript - 元数据版本不匹配 Angular 4 @ng-bootstrap

javascript - 如何在 Phonegap 中使用 JavaScript 将数据从一个 html 传递到另一个 html 页面?

javascript - 如何在 Typescript 和 React.js 中使用随机字段解析 JSON

reactjs - 当状态发生变化时,如何正确更新 react native 滑动器组件?

javascript - 获取哈希中唯一条目的值

javascript - 一键上传文件并发布文本输入值?

go - 编码为 JSON 时将类型 int 转换为 const 名称的字符串