spring启用cors_在Go Web服务器上启用CORS

spring启用cors

CORS stands for Cross Origin Resource Sharing and it’s a very handy way to make an API accessible by JavaScript in-browser client-side code.

CORS代表跨源资源共享 ( Cross Origin Resource Sharing) ,它是使JavaScript浏览器客户端代码可访问API的一种非常便捷的方法。

If you are looking for a simple, quick way to enable CORS in localhost, or to open your API to anyone in the world, use:

如果您正在寻找一种简单快捷的方法来在localhost中启用CORS,或向世界上任何人打开API,请使用:

func handler(w http.ResponseWriter, req *http.Request) {
    // ...
	enableCors(&w)
    // ...
}

func enableCors(w *http.ResponseWriter) {
	(*w).Header().Set("Access-Control-Allow-Origin", "*")
}

This does not provide any kind of control or fine tuning, and it’s intended for testing purposes only. Take a look at https://github.com/rs/cors for a more advanced setup.

这不提供任何控制或微调,仅用于测试目的。 看看https://github.com/rs/cors以获得更高级的设置。

处理飞行前OPTIONS请求 (Handling pre-flight OPTIONS requests)

CORS does pre-flight requests sending an OPTIONS request to any URL, so to handle a POST request you first need to handle an OPTIONS request to that same URL.

CORS会进行飞行前请求,将OPTIONS请求发送到任何URL,因此,要处理POST请求,您首先需要处理对该相同URL的OPTIONS请求。

On GET endpoints this is not an issue, but it is for POST and PUT and DELETE requests.

在GET端点上,这不是问题,但它适用于POST,PUT和DELETE请求。

How?

怎么样?

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 indexHandler(w http.ResponseWriter, req *http.Request) {
	setupResponse(&w, req)
	if (*req).Method == "OPTIONS" {
		return
	}

    // process the request...
}

Again, this is intended for private use CORS only. Public use needs to be restricted.

同样,这仅适用于私人使用的CORS。 需要限制公共使用。

翻译自: https://flaviocopes.com/golang-enable-cors/

spring启用cors

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值