javascript - Javascript fetch api 使用 golang mux 路由器获取 404 响应
问题描述
我正在尝试使用 Fetch API 和 Gorilla mux Router.Handle 函数将 JSON 数据发布到我的本地服务器,但即使我正确输入了 URL,它也总是返回 404 状态代码。我设法通过输入 localhost:3000 在 GO 本地服务器中运行和呈现我的 HTML、CSS 和 JS 文件
这是我的代码
索引.html
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="heading">Testing 123</h1>
<button onclick="Go()">HELLO WORLD</button>
<script src="script.js"></script>
</body>
</html>
脚本.js
function Go() {
var url = "http://localhost:3000/testing";
data = {};
data.name = "Jeff";
data.age = 24
data.isAlive = true;
defaultFetchParam = {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
fetch(url, defaultFetchParam)
.then(function (response) {
console.log("response", response)
return response.json()
})
.then(function (result) {
console.log("result", result);
})
}
main.go
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/GeertJohan/go.rice"
"github.com/gorilla/mux"
"github.com/rs/cors"
)
type People struct {
Name string `json:"name"`
Age int64 `json:"age"`
IsAlive bool `json:"isAlive"`
}
func main() {
//Init Router
router := mux.NewRouter()
router.PathPrefix("/").Handler(http.FileServer(rice.MustFindBox("webTest").HTTPBox()))
router.HandleFunc("/testing", testingFeature).Methods("POST")
corsOpts := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "HEAD", "OPTIONS", "PUT"},
AllowCredentials: true,
AllowedHeaders: []string{"Content-Type", "Access-Control-Allow-Origin"},
OptionsPassthrough: true,
})
handler := corsOpts.Handler(router)
http.ListenAndServe(":3000", handler)
}
func testingFeature(w http.ResponseWriter, r *http.Request) {
var people People
getInfo := json.NewDecoder(r.Body).Decode(&people)
fmt.Println("getInfo", getInfo)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(getInfo)
}
解决方案
推荐阅读
- java - 如何更改文档的版本?
- symfony - 如何通过IP自动改变环境
- asp.net-mvc - 即使从模型和控制器中删除,必填字段验证器仍会触发
- python - 如何找到总和为特定数字的所有数字对
- opencv - 获取错误:在 Ubuntu 16 上构建项目时找不到 -lopencv_dep_cudart
- java - 无法为片段事务获得正确的设计
- java - 我想将数据从 mysql 加载到 jsp,但我有一个无法处理的错误
- android - 在 Chrome 浏览器的登录页面触发自动填充服务
- java - 在类的私有静态最终字段中模拟静态方法调用
- javascript - 每行限制为 1 个字符的 JS 函数声明?