javascript - 我无法让 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 函数。我应该如何从我的获取请求中获取参数?
解决方案
你还没有使用你的多路复用路由器。由于您传递nil
到ListenAndServe
,它使用的是默认路由器,该路由器附加了所有其他处理程序。相反,将所有处理程序注册到您的多路复用路由器,然后将其作为第二个参数传递给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)
}
推荐阅读
- python - Python - 是否可以使用空白列创建连接字符串
- php - 如何从选定的月份获取上个月
- ionic-framework - ionic 3 从标签页到普通页
- c# - 如何从另一个类调用 IWebElement 方法?
- curl - PHP 7.1 oAuth 扩展,带有使用 Curl 的请求引擎支持 - OAUTH_REQENGINE_CURL
- php - .Net 应用程序关闭时使用 PHP 在 SQL Server 2008 上进行缓慢查询
- perl - DBIx::Class::ResultSet::count(): DBI Connection failed: DBD::Oracle at /usr/share/perl5/DBIx/Class/Storage/DBI.pm line 1249
- c# - 为什么serila数据传输会跳过c#中的特定数据模式?
- c# - 如何使用已生成的令牌上传 youtube 视频?
- javascript - 为什么 DateTimePicker 的日历不弹出?