登录
首页 >  Golang >  Go问答

无法显示 JSON 数据在 AG 格网中,只是显示加载中

来源:stackoverflow

时间:2024-03-20 10:18:29 293浏览 收藏

由于浏览器安全限制,跨域 HTTP 请求被阻止,导致 Angular 应用程序无法从本地 Go 服务中获取 JSON 数据。要解决此问题,需要在 Go 服务器中启用 CORS(跨域资源共享)支持,允许应用程序从不同的域访问数据。这可以通过使用 gorilla/handlers 或 rs/cors 库来实现,它们允许在响应中设置适当的 CORS 标头。

问题内容

使用我在网上找到的各种示例,我拼凑了一个简单的网络应用程序。然而,尽管 ag grid(我选择用来显示数据的网格)可以与提供的数据源配合使用,但它不能与我自己的数据源配合使用,该数据源是使用 go 编写的 web 服务创建的。

角度代码...

ngoninit() {
  this.rowdata = this.http.get('https://api.myjson.com/bins/ly7d1'); 
}

这可以正确显示网格上的数据。但是当我将其重定向到我时,go 使用以下命令生成数据...

ngoninit() {   
  this.rowdata = this.http.get('http://localhost:10000/all');
}

这个网格只是说正在加载...

如果我在浏览器中测试任一链接,我会得到以完全相同的方式格式化的完全相同的数据...

[{"make":"toyota","model":"celica","price":35000},{"make":"ford","model":"mondeo","price":32000},{"make":"porsche","model":"boxter","price":72000},{"make":"toyota","model":"celica","price":35000},{"make":"ford","model":"mondeo","price":32000},{"make":"porsche","model":"boxter","price":72000},{"make":"toyota","model":"celica","price":35000},{"make":"ford","model":"mondeo","price":32000},{"make":"porsche","model":"boxter","price":72000},{"make":"toyota","model":"celica","price":35000},{"make":"ford","model":"mondeo","price":32000},{"make":"porsche","model":"boxter","price":72000}]

这是 json 的链接:

https://api.myjson.com/bins/ly7d1

我在同一台机器上运行我的 angular 应用程序和 go 应用程序,但有不同的服务并使用不同的端口...

我可以包含 go 代码,但我不知道它有多相关,因为数据在浏览器中正确显示。

尝试只包含相关的内容,但如果我遗漏了某些内容,请告诉我,我可以上传。

html 代码...


welcome to {{ title }}!

angular logo

here are some links to help you start:

预期输出...

go web 服务代码...

package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"

    _ "github.com/go-sql-driver/mysql"
)

// Article - Our struct for all articles
type Article struct {

    Make string `json:"make"`
    Model   string `json:"model"`
    Price int32 `json:"price"`
}

type Articles []Article

func homePage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to the HomePage!")
    fmt.Println("Endpoint Hit: homePage")
}

func returnAllArticles(w http.ResponseWriter, r *http.Request) {
    articles := Articles{
        Article{Make: "Toyota", Model: "Celica", Price: 35000},
        Article{Make: "Ford", Model: "Mondeo", Price: 32000},
        Article{Make: "Porsche", Model: "Boxter", Price: 72000},
        Article{Make: "Toyota", Model: "Celica", Price: 35000},
        Article{Make: "Ford", Model: "Mondeo", Price: 32000},
        Article{Make: "Porsche", Model: "Boxter", Price: 72000},
        Article{Make: "Toyota", Model: "Celica", Price: 35000},
        Article{Make: "Ford", Model: "Mondeo", Price: 32000},
        Article{Make: "Porsche", Model: "Boxter", Price: 72000},
        Article{Make: "Toyota", Model: "Celica", Price: 35000},
        Article{Make: "Ford", Model: "Mondeo", Price: 32000},
        Article{Make: "Porsche", Model: "Boxter", Price: 72000},
    }
    fmt.Println("Endpoint Hit: returnAllArticles")

    json.NewEncoder(w).Encode(articles)
}



type Tag struct {
    JN   string    `json:"jobno"`
    Title string `json:"title"`
}

func returnSingleArticle(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    key := vars["id"]
    fmt.Fprintf(w, "Key: "+key)
}

func handleRequests() {
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)

    myRouter.HandleFunc("/all", returnAllArticles)  
    log.Fatal(http.ListenAndServe(":10000", myRouter))
}

func main() {
    handleRequests()
}

更新 我现在已经尝试了以下... 完全重写了我的 macbook 上的网站和服务 尝试在服务器和客户端上使用不同的端口 尝试在另一台机器上运行服务器 禁用所有防火墙

这些都没有任何区别。


解决方案


您无法获取数据,因为出于安全原因,您的浏览器阻止了从 http://localhost:4200http://localhost:10000/all 的跨域 http 请求。您的 go 服务器必须能够处理预检 options 请求并在响应中发送正确的 CORS 标头。

使用 gorilla/handlersrs/cors 启用 cors 支持。

import (
    "net/http"   
    "github.com/gorilla/mux"
    "github.com/gorilla/handlers"
    "github.com/rs/cors"          
)

func handleRequests() {
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage) 
    myRouter.HandleFunc("/all", returnAllArticles)

    // ----- OPTION 1 ----- Use rs/cors
    corsOptions := cors.New(cors.Options{
        AllowedHeaders: []string{"X-Requested-With", "Content-Type"},
        AllowedOrigins: []string{"*"}, // instead of '*' you can add the urls you want to allow e.g. 'http://localhost:4200'          
        AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodOptions, http.MethodHead}
    })
    log.Fatal(http.ListenAndServe(":10000", corsOptions.Handler(myRouter))
    // --------------------------------


    // ----- OPTION 2 ----- Use gorilla/handlers
    corsHeaders := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
    corsOrigins := handlers.AllowedOrigins([]string{"*"})
    corsMethods := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
    log.Fatal(http.ListenAndServe(":10000", handlers.CORS(corsHeaders, corsOrigins, corsMethods)(myRouter)))
    // --------------------------------
}

func main() {
    handleRequests()
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>