首页 文章

在预检请求中发送自定义 Headers OPTIONS angular 5

提问于
浏览
0

我已经构建了一个带有角度5的应用程序,它连接到用golang开发的REST API,并托管在端口8080上运行的aws ec2实例上 . 我的角度前端代码创建了一个POST请求,在发出请求之前,浏览器首先发送一个COR预检请求,失败并显示以下错误消息:

阻止跨源请求:同源策略禁止在https://signup.mysite.com:8080/api/v1/merchant/signup上读取远程资源 . (原因:在CORS预检 Channels 的CORS Headers 'Access-Control-Allow-Headers'中缺少令牌'access-control-allow-credentials') .

浏览器在OPTIONS请求中将以下标头发送到REST API服务器:

Access-Control-Request-Headers : access-control-allow-credentia…rol-allow-origin,content-type
Access-Control-Request-Method : POST

在golang上启用Cors但不确定它们是否正常工作 . 我该如何解决这个问题

编辑使用以下代码在角度5中的帖子请求中添加 Headers

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())

2 回答

  • 1

    你必须从服务器端代码启用cors .

    func setupResponse(w *http.ResponseWriter, req *http.Request) {
        (*w).Header().Set("Access-Control-Allow-Origin", "*")
        (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        (*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    }
    
    func yourApi(w http.ResponseWriter, req *http.Request) {
        setupResponse(&w, req) 
    
        // process the request...
    }
    
  • 0

    您可以在Chrome的本地副本上开发期间禁用CORS . 如果您使用的是MAC OS,请在终端中输入以下命令:

    open -a Google\ Chrome --args --disable-web-security --user-data-dir
    

    此步骤会禁用多个(如果不是全部)Chrome安全功能,因此请谨慎操作 . 如果您无法控制服务器端并允许您继续开发,这将消除您的错误 .

相关问题