gpt4 book ai didi

ajax - 在 Golang 中启用 CORS

转载 作者:IT王子 更新时间:2023-10-29 01:09:56 24 4
gpt4 key购买 nike

您好,我正在实现 rest api,为此我想允许处理跨源请求。

我现在在做什么:

AWS 上的 Go 服务器代码:

func (c *UserController) Login(w http.ResponseWriter, r *http.Request, ctx *rack.Context) {
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
...
...
c.render.Json(w,rsp, http.StatusOK)
return
}

本地主机上的 Ajax 代码:

<script>
$( document ).ready(function() {
console.log( "ready!" );
$.ajax({
url: 'http://ip:8080/login',
crossDomain: true, //set as a cross domain requests
withCredentials:false,
type: 'post',
success: function (data) {
alert("Data " + data);
},
});
});

我在浏览器控制台上收到以下错误:XMLHttpRequest 无法加载 http://ip:8080/login .请求的资源上不存在“Access-Control-Allow-Origin” header 。产地' http://localhost:8081 ' 因此不允许访问。响应的 HTTP 状态代码为 422。

我尝试添加预检选项:

func corsRoute(app *app.App) {
allowedHeaders := "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization,X-CSRF-Token"

f := func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
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", allowedHeaders)
w.Header().Set("Access-Control-Expose-Headers", "Authorization")
}
return
}
app.Router.Options("/*p", f, publicRouteConstraint)
}

但它不起作用。

可以做些什么来修复它。

最佳答案

我使用gorilla/mux包搭建Go RESTful API服务器,客户端使用JavaScript Request即可,

我的 Go 服务器运行在 localhost:9091,服务器代码:

router := mux.NewRouter()
//api route is /people,
//Methods("GET", "OPTIONS") means it support GET, OPTIONS
router.HandleFunc("/people", GetPeopleAPI).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":9091", router))

我发现在这里提供OPTIONS很重要,否则会发生错误:

OPTIONS http://localhost:9091/people 405 (Method Not Allowed)

Failed to load http://localhost:9091/people: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9092' is therefore not allowed access. The response had HTTP status code 405.

在允许 OPTIONS 后效果很好。我的想法来自 This Article .

此外,MDN CORS doc提及:

Additionally, for HTTP request methods that can cause side-effects on server's data, the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.

以下是apiGetPeopleAPI方法,在方法中注意我给出的注释//Allow CORS here By * or specific origin,我有另一个类似的答案解释这个概念CORS Here :

func GetPeopleAPI(w http.ResponseWriter, r *http.Request) {

//Allow CORS here By * or specific origin
w.Header().Set("Access-Control-Allow-Origin", "*")

w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
// return "OKOK"
json.NewEncoder(w).Encode("OKOK")
}

在客户端中,我在 localhost:9092 上使用 html 和 javascript,javascript 将从 localhost:9092 向服务器发送请求

function GetPeople() {
try {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:9091/people", false);
xhttp.setRequestHeader("Content-type", "text/html");
xhttp.send();
var response = JSON.parse(xhttp.response);
alert(xhttp.response);
} catch (error) {
alert(error.message);
}
}

并且请求可以成功得到响应"OKOK"

您还可以通过 Fiddler 等工具查看响应/请求头信息。

关于ajax - 在 Golang 中启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39507065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com