相当新的后端,特别是在Go中。我发现很难理解后端如何/应该如何与前端通信,尤其是在后端。
例如,我在Go中有一个简单的模拟Books API,我希望将响应从Go传递到React。
package main
import (...)
var books []Book
func main() {
// initialize router
r := mux.NewRouter()
books = append(books, []Book{
{
ID: "1",
Isbn: "23423",
Title: "Book 1",
Author: &Author{
FirstName: "Nas",
LastName: "Ahm",
},
},
{
ID: "2",
Isbn: "97878",
Title: "Book 2",
Author: &Author{
FirstName: "Has",
LastName: "Ahm",
},
},
}...)
// router endpoints
r.HandleFunc("/api/books", getBooks).Methods("GET")
log.Fatal(http.ListenAndServe(":3000", r))
}
func getBooks(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "application/json")
json.NewEncoder(writer).Encode(books)
}
问题是,如何将Books数据传递给Frontend(反应)?