我正在使用Go和Javascript开发Webapp。我还使用Google Compute Engine来提供我的应用程序。我有3个VM,一个用于我的数据库,一个用于前端,最后一个用于后端。使用Go从数据库中恢复数据没有任何问题,但是当我尝试将数据从Go发送到Javascript时,出现了此错误消息

GET http://10.132.0.3/ 0 ()    (index):10
    callGoServer    @   (index):10
    onclick @   (index):15

Uncaught (in promise) TypeError: Failed to fetch    (index):1
    Promise.then (async)
    callGoServer    @   (index):12
    onclick @   (index):15

这是我的Go代码
package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
    "log"
    "net/http"

    _ "github.com/lib/pq"
)

//Quote is a quote
type Quote struct {
    ID     int `json:"id"`
    Phrase string `json:"phrase"`
    Author string `json:"author"`
}

var db *sql.DB

func init() {
    var err error
    db, err = sql.Open("postgres", "postgres://postgres:[email protected]:5432/quotes?sslmode=disable")
    if err != nil {
        panic(err)
    }

    if err = db.Ping(); err != nil {
        panic(err)
    }
    fmt.Println("You connected to your database")
}

func getQuotes(w http.ResponseWriter, r *http.Request) {

    if r.Method != "GET" {
        http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
        return
    }

    rows, err := db.Query("SELECT id, phrase, author FROM citations ORDER BY RANDOM() LIMIT 1;")
    if err != nil {
        http.Error(w, http.StatusText(500), 500)
        return
    }
    defer rows.Close()

    quotations := make([]Quote, 0)
    for rows.Next() {
        qt := Quote{}
        err := rows.Scan(&qt.ID, &qt.Phrase, &qt.Author)
        if err != nil {
            panic(err)
        }
        quotations = append(quotations, qt)
    }
    if err = rows.Err(); err != nil {
        panic(err)
    }

    for _, qt := range quotations {
        payload, _ := json.Marshal(qt)
        w.Header().Add("Content-Type", "application/json")
        w.Write(payload)
    }
}

func main() {
    router:= mux.NewRouter()
    router.HandleFunc("/", getQuotes)
    log.Fatal(http.ListenAndServe(":8080",handlers.CORS(handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}),handlers.AllowedMethods([]string{"GET","POST","PUT","DELETE"}),handlers.AllowedOrigins([]string{"*"}))(router)))
}

这是我的JS代码
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Random quote</title>
    </head>
    <body>
        <script type="text/javascript" language="javascript">
            function callGoServer(){
                fetch('http://10.132.0.3')
                    .then(response => response.json())
                    .then(json => console.log(json))
            }
        </script>
        <button onclick="callGoServer()">Click here</button>
    </body>
</html>

我在GCP上制定了防火墙规则,该规则允许VM通过端口5432(postgresql)和8080(我的go服务器)在VM之间进行TCP协议(protocol)

有人可以帮我吗?

谢谢

最佳答案

您的VM仅具有private IP address。您无法从浏览器访问它。您需要assign a public IP address到您的VM并使用它。

解决之后,您仍然需要在正确的端口上发出请求。您正在监听端口8080,但在您的请求中未指定端口,因此它使用默认的http端口(80)。

将您的请求更改为

function callGoServer(){
  fetch('http://10.132.0.3:8080')
    .then(response => response.json())
    .then(json => console.log(json))
}

或改为监听端口80。

关于javascript - 两个Google计算引擎实例之间的连接问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52291137/

10-17 00:53