登录
首页 >  Golang >  Go问答

在 Go Web-Server 和 Vue.js 前端之间实现数据交换的方法

来源:stackoverflow

时间:2024-02-20 21:54:29 492浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《在 Go Web-Server 和 Vue.js 前端之间实现数据交换的方法》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我试图了解如何在非常精简的 golang web 服务器和 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, puser{first_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 web 服务器:

(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 服务器和 vue.js 前端之间正确交换数据? 期待您的好意帮助。 马可


解决方案


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

理论要掌握,实操不能落!以上关于《在 Go Web-Server 和 Vue.js 前端之间实现数据交换的方法》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>