无法显示 JSON 数据在 AG 格网中,只是显示加载中
由于浏览器安全限制,跨域 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 代码...
<!--the content below is only a placeholder and can be replaced.--> <div style="text-align:center"> <h1> welcome to {{ title }}! </h1> <img width="300" alt="angular logo" src="data:image/svg+xml;base64,phn2zyb4bwxucz0iahr0cdovl3d3dy53my5vcmcvmjawmc9zdmciihzpzxdcb3g9ijagmcayntagmjuwij4kicagidxwyxroigzpbgw9iinerdawmzeiigq9ik0xmjugmzbmmzeuosa2my4ybde0ljigmtizljfmmti1idizmgw3oc45ltqzljcgmtqumi0xmjmumxoiic8+ciagica8cgf0acbmawxspsijqzmwmdjgiibkpsjnmti1idmwdjiyljitljfwmjmwbdc4ljktndmunyaxnc4ylteymy4xtdeynsazmhoiic8+ciagica8cgf0acagzmlsbd0ii0zgrkzgriigzd0itteynsa1mi4xtdy2ljggmtgyljzomjeun2wxms43lti5ljjondkungwxms43idi5ljjimtgztdeynsa1mi4xem0xnya4my4zac0zngwxny00mc45ide3idqwljl6iiavpgogidwvc3znpg=="> </div> <h2>here are some links to help you start: </h2> <ul> <li> <h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">tour of heroes</a></h2> </li> <li> <h2><a target="_blank" rel="noopener" href="https://angular.io/cli">cli documentation</a></h2> <button (click)="onbtexport()">export to csv</button> <ag-grid-angular #aggrid style="width: 500px; height: 500px;" class="ag-theme-balham" [rowdata]="rowdata | async" [columndefs]="columndefs" rowselection="multiple" > </ag-grid-angular> </li> <li> <h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">angular blog</a></h2> </li> </ul>
预期输出...
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:4200
到 http://localhost:10000/all
的跨域 http 请求。您的 go 服务器必须能够处理预检 options
请求并在响应中发送正确的 CORS 标头。
使用 gorilla/handlers
或 rs/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学习网公众号。

- 上一篇
- 深入探讨Linux归档功能并提供实践指南

- 下一篇
- Linux Bashrc指南:功能、配置和用法
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 茅茅虫AIGC检测
- 茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
- 86次使用
-
- 赛林匹克平台(Challympics)
- 探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
- 93次使用
-
- 笔格AIPPT
- SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
- 97次使用
-
- 稿定PPT
- 告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
- 91次使用
-
- Suno苏诺中文版
- 探索Suno苏诺中文版,一款颠覆传统音乐创作的AI平台。无需专业技能,轻松创作个性化音乐。智能词曲生成、风格迁移、海量音效,释放您的音乐灵感!
- 91次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览