如何将值从 golang 发送到 vue js(服务器到客户端)?

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

这里是超级新手开发者。所以说我在 golang 中有一个变量(键)(即类型字符串),我想发送客户端(Vue js)。我试过在本地发送它,但 Vue js 无法读取它。所以我 100% 确定我在 golang 中做错了。

我是否需要 POST 它到本地服务器(例如:localhost:3001)并从 vue js 获取它? 我应该如何发送这个 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 上显示它?谢谢。

如果不确切了解您的 Go 代码是如何编写的,就很难完全理解您在这方面所做的事情,尤其是因为您说:

So I'm 100% sure I'm doing it wrong within 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 应用程序中,您需要从返回的数据响应中提取“消息”数据,因为仅使用“数据”将包含与实际“消息”无关的其他信息,例如状态码。

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

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