如何在 Go Web-Server 和 Vue.js 前端之间交换数据? http-post : 404

Posted

技术标签:

【中文标题】如何在 Go Web-Server 和 Vue.js 前端之间交换数据? http-post : 404【英文标题】:How to exchange data between Go Web-Server and Vue.js frontend? http-post : 404 【发布时间】:2020-08-14 14:50:53 【问题描述】:

我正在尝试了解如何在非常精简的 golang 网络服务器和 vue.js 前端之间交换数据。

这是 server-gorillamux.go 文件:

package main

import (
        "encoding/json"
        "github.com/gorilla/mux"
        "log"
        "net/http"
)

const (
        CONN_HOST = "192.168.1.7"
        CONN_PORT = "3000"
)

type Puser struct 
        first_name   string `json:"first_name"`
        last_name    string `json:"last_name"`
        company_name string `json:"company_name"`
        email        string `json:"email"`
        tel          string `json:"tel"`


type Pusers []Puser

var pusers []Puser

type Route struct 
        Name        string
        Method      string
        Pattern     string
        HandlerFunc http.HandlerFunc


type Routes []Route

var routes = Routes
        Route
                "getPusers",
                "GET",
                "/pusers",
                getPusers,
        ,
        Route
                "addPuser",
                "POST",
                "/puser/add",
                addPuser,
        ,


func getPusers(w http.ResponseWriter, r *http.Request) 
        json.NewEncoder(w).Encode(pusers)


func addPuser(w http.ResponseWriter, r *http.Request) 
        puser := Puser
        err := json.NewDecoder(r.Body).Decode(&puser)
        if err != nil 
                log.Print("error occured while decoding puser data :: ", err)
        
        log.Printf("adding puser id :: % s with firstName ass :: %s and lastName as :: %s ",   
                puser.first_name, puser.last_name)
        pusers = append(pusers, Puserfirst_name: puser.first_name,
                last_name: puser.last_name, company_name: puser.company_name,
                email: puser.email, tel: puser.tel)
        json.NewEncoder(w).Encode(pusers)


func AddRoutes(router *mux.Router) *mux.Router 
        for _, route := range routes 
                router.
                        Methods(route.Method).
                        Path(route.Pattern).
                        Name(route.Name).
                        Handler(route.HandlerFunc)
         
        return router
 

func main() 
        muxRouter := mux.NewRouter().StrictSlash(true)
        router := AddRoutes(muxRouter)
        router.PathPrefix("/").Handler(http.FileServer(http.Dir("../src/components
/auth/Forms.vue")))
        //router.PathPrefix("/").Handler(http.FileServer(http.Dir("../public/")))
        err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
        if err != nil 
                log.Fatal("error starting http server :: ", err)
                return
        

这是 /src/components/auth/Forms.vue 文件:

<template>
  <div id="signupform">
    <div class="signup-form">
      <form @submit.prevent="onSubmit">
        <div class="firstname">
          <label for="firstname">First Name</label>
          <input
                 type="string"
                 id="firstname"
                 v-model="firstname" placeholder="First Name">
        </div>
        <div class="lastname">
          <label for="lastname">Last Name</label>
          <input
                 type="string"
                 id="lastname"
                 v-model="lastname" placeholder="Last Name">
        </div>
        <div class="companyname">
          <label for="companyname">Company Name</label>
          <input
                 type="string"
                 id="companyname"
                 v-model="companyname" placeholder="Company Name">
        </div>
        <div class="input">
          <label for="email">Mail</label>
          <input
                  type="email"
                  id="email"
                  v-model="email" placeholder="e-mail">
        </div>
        <div class="input">
          <label for="tel">Telephone Number</label>
          <vue-tel-input v-model="tel"></vue-tel-input>
        </div>
        <div class="input inline">
      <input type="checkbox" id="terms" v-model="terms">
          <label for="terms">Accept Terms of Use</label>
        </div>
        <div class="submit">
          <button type="submit">Submit</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
  //import axios from '../../axios-auth';

  import Vue from 'vue';
  import  VueTelInput  from 'vue-tel-input';

  Vue.use(VueTelInput);

  export default 
    components: 
      VueTelInput,
    ,
    data () 
      return 
        firstname: '',
        lastname: '',
        companyname: '',
        email: '',
        tel: '',
        terms: false
      
    ,
    methods: 
      onSubmit () 
        const formData = 
          first_name: this.firstname,
          last_name: this.lastname,
          company_name: this.lastname,
          email: this.email,
          tel: this.tel,
          terms: this.terms
        
        this.addPuser(formData);
      ,
      addPuser (fdata) 
        this.$http.post('/puser/add', 
            fdata
            //first_name:this.firstname,
            //last_name:this.lastname,
            //company_name:this.companyname,
            //email:this.email,
            //tel: this.tel
          ).then(response => 
              console.log(response);
           , error => 
             console.error(error);
          );
      
     // end of methods
  
</script>

<style scoped>
    ....
</style>

执行 golang 网络服务器:

(base) marco@pc01:~/webMatters/vueMatters/GraspGlobalChances/goServer$ go run server-  
gorillamux.go

以及编译和运行 vue.js 前端

DONE Compiled successfully in 1960ms 4:37:20 PM

App running at:

    Local: http://localhost:8080
    Network: http://ggc.world/

更新 1)

这些是 /var/log/nginx/ggcworld-access.log 的最后几行,对应于我上次的 POST 尝试:

2.36.119.16 - - [30/Apr/2020:16:01:41 +0200] "GET / HTTP/2.0" 200 694 
"-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (Khtml, like 
Gecko) Chrome/81.0.4044.129 Safari/537.36"
2.36.119.16 - - [30/Apr/2020:16:01:41 +0200] "GET /js/app.js HTTP/2.0"
200 147353 "https://ggc.world/" "Mozilla/5.0 (X11; Linux x86_64)   
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/$
2.36.119.16 - - [30/Apr/2020:16:01:42 +0200] "GET /js/chunk-vendors.js
HTTP/2.0" 200 4241853 "https://ggc.world/" "Mozilla/5.0 (X11; Linux 
x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.$
2.36.119.16 - - [30/Apr/2020:16:01:42 +0200] "GET /sockjs-
node/info?t=1588255302671 HTTP/2.0" 200 79 "https://ggc.world/"    
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like 
Gecko) Chrome/81$
2.36.119.16 - - [30/Apr/2020:16:03:50 +0200] "POST /puser/add 
HTTP/2.0" 404 137 "https://ggc.world/" "Mozilla/5.0 (X11; Linux 
x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 
Safari/53$

如何在 golang web-server 和 vue.js 前端之间正确交换数据? 期待您的帮助。 马可

【问题讨论】:

您的后端服务器似乎没有/puser/add 路由。 @bgnfu7re 你好!!这是否意味着以下内容还不够?在 server-gorillamux.go 中: var routes = Routes Route "getPusers", "GET", "/pusers", getPusers, , Route "addPuser", "POST", "/puser/add", addPuser, , @Arpit Aggarwal 你能看一下吗? 我已经启动了你的后端,它可以工作。路线服务正确。检查谁是您的前端呼叫者。它可能是错误的服务器。附带说明一下,Puser 结构将无法工作,因为它包含不可导出的字段。 【参考方案1】:

看起来您的后端服务器运行在端口3000,而您的前端运行在端口8080。如果是,那么请在您的前端应用程序中配置代理规则以下文档 - API Proxying During Development

【讨论】:

嗨@Arpit Aggarwal!我的前端应用程序在端口 8080 上运行,因为它依赖于 nginx 代理服务器。您认为可以将 golang 网络服务器与 nginx 网络服务器结合使用吗? 是的,有可能,我可以看到后端已启动并运行,/puser/add 可供前端使用,请检查请求是否命中 Nginx? 我用 /var/log/nginx/ggcworld-access.log 的最后几行更新了我的问题,对应于我上次的 POST 尝试 我相信你在 Nginx 中配置了反向代理? - docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy 是的。配置为:location / proxy_pass 127.0.0.1:8080;

以上是关于如何在 Go Web-Server 和 Vue.js 前端之间交换数据? http-post : 404的主要内容,如果未能解决你的问题,请参考以下文章

Java web-server 应用程序有没有办法推送?

《Vue.j实战》一书 p171 练习 2 试做

分布式事务产生场景

一致性(转)

nginxkeepalivedlvsf5可以很好的解决高可用扩展性反向代理+扩展均衡的问题

centos7下安装docker(23.docker-swarm之如何访问service)