如何用JavaScript调用我的Go服务器?

问题描述 投票:0回答:2

我正在使用Go,JavaScript和PostgreSQL开发一个Web应用程序。

将Go程序与数据库链接起来没有任何问题。但是我遇到了一些JavaScript问题。

这是我的Go代码连接到我的数据库,当我调用localhost:8080时返回我的表的随机元素:

type Quote struct {
    ID     int
    Phrase string
    Author string
}

var db *sql.DB



func init() {
    var err error
    db, err = sql.Open("postgres", "postgres://gauthier:password@localhost/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() {
    http.HandleFunc("/", getQuotes)
    http.ListenAndServe(":8080", nil)
}

当我运行这个程序并使用curl -i localhost:8080时,它会返回我的预期,来自我的数据库的随机引用

`gauthier@gauthier-Latitude-7280:~/gocode/sprint0$ curl -i localhost:8080
 HTTP/1.1 200 OK
 Content-Type: application/json
 Date: Thu, 30 Aug 2018 12:28:00 GMT
 Content-Length: 116

 {"ID":7,"Phrase":"I've never had a problem with drugs. I've had problems with the police","Author":"Keith Richards"}`

现在,当我尝试使用JavaScript而不是curl使用那个小脚本发出相同的请求时:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Random quote</title>
  </head>
  <body>
    <script type="text/javascript" language="javascript">
      function getQuotations() {
         httpRequest= new XMLHttpRequest();
         httpRequest.onreadystatechange = function() {
             alertContents(httpRequest)
         };
         httpRequest.open("GET", "http://localhost:8080", true);
      }

      function alertContents(httpRequest) {
          console.log("http status: "+httpRequest.status);
          console.log("http response: "+httpRequest.responseText);
      }
    </script>
    <button onclick="getQuotations()">Click here for a quotation</button>
  </body>
</html>

当我点击按钮并打开Chromium的控制台时,我得到:

http status: 0            hello.html:18 
http response:            hello.html:19

有人能帮我吗?

javascript http xmlhttprequest
2个回答
0
投票

尝试使用XMLHttpRequest略有不同,以便您使用load事件:

 httpRequest= new XMLHttpRequest();
  httpRequest.load= function() {
             alertContents(this.responseText)
  };
  httpRequest.open("GET", "http://localhost:8080", true);
  httpRequest.send();

0
投票

如果你对Promises感到满意的话,我觉得这可以用fetch简化。你不必处理readystatechangestatus代码等。这是一个例子。

function getQuotations() {
  return fetch('http://localhost:8080')
    .then(response => response.json())
    .then(alertContents)
    .catch(console.error);
}

function alertContents(contents) {
  console.log(contents);
  alert(`"${contents.Phrase}" ~${contents.Author}`);
}
© www.soinside.com 2019 - 2024. All rights reserved.