【发布时间】:2018-11-18 09:15:08
【问题描述】:
我用 Angular 5 构建了一个应用程序,该应用程序连接到使用 golang 开发的 REST API,并托管在端口 8080 上运行的 aws ec2 实例上。我的 Angular 前端代码创建了一个 POST 请求,在发出该请求之前,浏览器首先发送 COR 预检请求,但失败并显示以下错误消息:
跨域请求被阻止:同源策略不允许读取 远程资源在
https://signup.mysite.com:8080/api/v1/merchant/signup。 (原因: CORS 标头中缺少令牌“访问控制允许凭据” 来自 CORS 预检通道的“Access-Control-Allow-Headers”)。
以下标头由浏览器在 OPTIONS 请求中发送到 REST API 服务器:
Access-Control-Request-Headers : access-control-allow-credentia…rol-allow-origin,content-type
Access-Control-Request-Method : POST
在 golang 上启用了 Cors,但不确定它们是否正常工作。我该如何解决这个问题
编辑 使用以下代码在 Angular 5 的 post 请求中添加标头
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
let headers = new HttpHeaders();
headers = headers.append('Access-Control-Allow-Origin', '*');
headers = headers.append('Access-Control-Allow-Credentials', 'true');
return this.http.post<Response>(this.apiUrl+'merchant/signup', JSON.stringify(formValues),{headers: headers}).map(response => response.response);'true');
以下代码在 go 文件中
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// host := strings.Split(c.Request.Host, ":8080")
c.Writer.Header().Set("Content-Type", "application/json")
// c.Writer.Header().Set("Access-Control-Allow-Origin", "http://"+host[0])
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
// c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Ip, X-Requested-With, access-control-allow-credentials ")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
}
也使用核心包
router.Use(cors.Default())
【问题讨论】:
-
显示启用的cors
-
@SachilaRanawaka 用标题更新了问题
-
从服务中设置标头。不要将其发送到服务器
-
@SachilaRanawaka 不明白你的意思,请解释一下
-
你使用的服务器端语言是什么
标签: angular go cors http-headers