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。 需要限制公共使用。
spring启用cors