首页 > 解决方案 > 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)
}

标签: javascriptgohttp-status-code-404fetch-apimux

解决方案


推荐阅读