I'm working on a webapp with Go and Javascript. I also use Google Compute Engine for serving my app. I have 3 VMs, one for my DB, on for the frontend and the last for the backend. I don't have any problem to recover datas from my DB with Go but when I'm try to send datas from Go to Javascript, I got this error message
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
Here's my Go code
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:password@10.132.0.2: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)))
}
Here's my JS code
<!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>
I've made a firewall rule on GCP that allow TCP protocol between my VM via port 5432
(postgresql) and 8080
(my go server)
Does someone can help me ?
Thanks
Your VM only has a private IP address. There is no way you can access this from your browser. You need to assign a public IP address to your VM and use that instead.
Once that's fixed, you still need to make the request on the correct port. You are listening on port 8080 but in your request you don't specify a port, so it uses the default http port (80).
Change your request to
function callGoServer(){
fetch('http://10.132.0.3:8080')
.then(response => response.json())
.then(json => console.log(json))
}
or listen on port 80 instead.