【发布时间】:2021-08-29 00:18:31
【问题描述】:
这里是超级新手开发者。所以说我在golang中有一个变量(键)(即类型字符串),我想发送客户端(Vue js)。我尝试在本地发送它,但 Vue js 无法读取它。所以我 100% 确定我在 golang 中做错了。
我需要将它发布到本地服务器(例如: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 上显示它?谢谢。
【问题讨论】:
-
服务器不发送请求,客户端发送。服务器发送对请求的响应。只需以客户端理解的格式将数据写入 http.ResponseWriter(JSON 是一个明显的选择)。
标签: javascript vue.js go localhost