问题描述

Access to XMLHttpRequest at ‘http://127.0.0.1:8888/base/captcha’ from origin ‘http://127.0.0.1:8080’ has been blocked by CORS policy: Cannot parse Access-Control-Allow-Headers response header field in preflight response.

127.0.0.1:8888后端的跨域策略为:

	origin := c.Request.Header.Get("Origin")
	c.Header("Access-Control-Allow-Origin", origin)
	c.Header("Access-Control-Allow-Headers", "Content-Type, AccessToken, X-CSRF-Token, Authorization, Token, x-token, x-user-id\"")
	c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
	c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
	c.Header("Access-Control-Allow-Credentials", "true")

注释掉第三行后

//c.Header("Access-Control-Allow-Headers", "Content-Type, AccessToken, X-CSRF-Token, Authorization, Token, x-token, x-user-id\"")

错误提示为:

Access to XMLHttpRequest at ‘http://127.0.0.1:8888/base/captcha’ from origin ‘http://127.0.0.1:8080’ has been blocked by CORS policy: Request header field x-token is not allowed by Access-Control-Allow-Headers in preflight response.

将第三行修改为:

c.Header("Access-Control-Allow-Headers", "*") //允许访问所有域

可以正常访问。

实际原因为第三行代码末尾多了一个引号“"”,删除后,如下

	origin := c.Request.Header.Get("Origin")
	c.Header("Access-Control-Allow-Origin", origin)
	c.Header("Access-Control-Allow-Headers", "Content-Type, AccessToken, X-CSRF-Token, Authorization, Token, x-token, x-user-id")
	c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
	c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
	c.Header("Access-Control-Allow-Credentials", "true")

可以正常访问。