我正在尝试在 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/