如何从Golang向Vue.js发送值(从服务器到客户端)?

huangapple go评论72阅读模式
英文:

How do I send values from golang to vue js (server to client)?

问题

超级新手开发者在这里。假设我在golang中有一个变量(key)(即类型为字符串),我想将其发送到客户端(Vue js)。我尝试在本地发送它,但Vue js无法读取它。所以我非常确定我在golang中做错了。

我需要将它POST到本地服务器(例如:localhost:3001),然后从vue js中获取它吗?
我应该如何在go中发送这个POST请求?有更好的选择吗?

当前vue代码片段:

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <p>Lorem</p>
  </div>

      <div v-if="key !== null">
    <p>{{key}}</p>
    </div>
    <div v-else>
      <p>Waiting for key....</p>
    </div>
    
</template>

<script>
export default {
  props: ['id'],
  data() {
    return {
      job: null,
      key: null,
    }
  },
  mounted() {

    fetch('http://localhost:3001', {
                    method: 'GET'
                })
      .then(res => res.json())
      .then(data => this.key = data.message)
      .catch(err => console.log(err.message))
  }
}
</script>

谢谢!

编辑:我的当前golang代码

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

type ResponseData struct {
	Message string `json:"message"`
}

func getData(w http.ResponseWriter, r *http.Request) {
	json.NewEncoder(w).Encode(ResponseData{Message: "Hello, World"})
}

func main() {
	http.HandleFunc("/", getData)

	fmt.Println("Server listening on port 3001")
	log.Panic(
		http.ListenAndServe(":3001", nil),
	)
}

当我访问http://localhost:3001/时,我能够看到消息{"message":"Hello, World"}。然而,当我在vue上运行GET命令时,我仍然没有收到任何东西。我在golang中做错了什么?另外,我如何编程以便我可以将自己的变量发送到getData()函数并在端口3001上显示它?谢谢。

英文:

super newbie developer here. So say I have a variable (key) (i.e. type string) in golang that I want to send client-side (Vue js). I've tried sending it locally but Vue js isn't able to read it. So I'm 100% sure I'm doing it wrong within golang.

Would I need to POST it to a local server (ex: localhost:3001) and GET it from vue js?
How should I send this POST request in go? Are there better options?

Snippet of current vue code :

&lt;template&gt;
  &lt;div class=&quot;about&quot;&gt;
    &lt;h1&gt;This is an about page&lt;/h1&gt;
    &lt;p&gt;Lorem&lt;/p&gt;
  &lt;/div&gt;

      &lt;div v-if=&quot;key !== null&quot;&gt;
    &lt;p&gt;{{key}}&lt;/p&gt;
    &lt;/div&gt;
    &lt;div v-else&gt;
      &lt;p&gt;Waiting for key....&lt;/p&gt;
    &lt;/div&gt;
    
&lt;/template&gt;

&lt;script&gt;
export default {
  props: [&#39;id&#39;],
  data() {
    return {
      job: null,
      key: null,
    }
  },
  mounted() {

    fetch(&#39;http://localhost:3001&#39;, {
                    method: &#39;GET&#39;
                })
      .then(res =&gt; res.json())
      .then(data =&gt; this.key = data.message)
      .catch(err =&gt; console.log(err.message))
  }
}
&lt;/script&gt;

Thank you!

EDIT: My current golang code

package main

import (
	&quot;encoding/json&quot;
	&quot;fmt&quot;
	&quot;log&quot;
	&quot;net/http&quot;
)

type ResponseData struct {
	Message string `json:&quot;message&quot;`
}

func getData(w http.ResponseWriter, r *http.Request) {
	json.NewEncoder(w).Encode(ResponseData{Message: &quot;Hello, World&quot;})
}

func main() {
	http.HandleFunc(&quot;/&quot;, getData)

	fmt.Println(&quot;Server listening on port 3001&quot;)
	log.Panic(
		http.ListenAndServe(&quot;:3001&quot;, nil),
	)
}

When I go http://localhost:3001/, I am able to see the message {&quot;message&quot;:&quot;Hello, World&quot;}. However, I am still not receiving anything when I run a GET command on vue. What am I doing wrong in golang? Also, how do I program it so that I can send my own variable to the getData() function and display it on port 3001? Thank you.

答案1

得分: 1

没有看到你的Go代码的具体编写方式,很难完全理解你在那一方面做了什么,特别是你说:

所以我非常确定我在golang中做错了

然而,为了填补空白,我假设你正在做以下操作:

type ResponseData struct {
    Message string `json:"message"`
}

func getData(w http.ResponseWriter, r *http.Request) {
    // CORS
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Authorization")

    json.NewEncoder(w).Encode(ResponseData{ Message : "Hello, World" })
}

在你的Vue应用程序中,你需要从返回的数据响应中提取那个"message"数据,因为只使用"data"将包含其他与实际"message"无关的信息,例如状态码。

fetch('http://localhost:3001')
  .then(res => res.json())
  .then(data => this.key = data.message)
  .catch(err => console.log(err.message))

我还假设你的Go服务器正在监听3001端口。

英文:

Without seeing exactly how your Go code is written it's difficult to fully understand what you're doing on that side, especially since you stated:

> So I'm 100% sure I'm doing it wrong within golang

However, as an example to fill in the blank, I'm going to make the assumption you're doing something like so:

type ResponseData struct {
    Message string `json:&quot;message&quot;`
}

func getData(w http.ResponseWriter, r *http.Request) {
    // CORS
    w.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)
    w.Header().Set(&quot;Access-Control-Allow-Methods&quot;, &quot;POST, GET, OPTIONS, PUT, DELETE&quot;)
    w.Header().Set(&quot;Access-Control-Allow-Headers&quot;, &quot;Accept, Content-Type, Content-Length, Authorization&quot;)


    json.NewEncoder(w).Encode(ResponseData{ Message : &quot;Hello, World&quot; }
}

From within your Vue application you'll need to extract that "message" data from the returned data response as using just "data" will include other information that isn't relevant to the actual "message" such as the status code.

fetch(&#39;http://localhost:3001&#39;)
  .then(res =&gt; res.json())
  .then(data =&gt; this.key = data.message)
  .catch(err =&gt; console.log(err.message))

I'm also assuming that your Go server is listening on port 3001.

huangapple
  • 本文由 发表于 2021年6月12日 17:25:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/67947432.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定