我正在尝试使用gorilla mux和google cloud端点构建一个API,但在允许跨源请求时遇到了问题。我在我的web应用程序中使用以下代码来发送请求:
$.ajax("https://my.api/echo", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + localStorage.id_token
},
data: JSON.stringify({
"message": this.query
})
}).done(function(response) {
console.log(response);
});在我的浏览器控制台中,我得到了以下错误:
OPTIONS https://my.api/echo 403 ()
Failed to load https://my.api/echo: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin
'http://127.0.0.1:8081' is therefore not allowed access. The response
had HTTP status code 403.端点的代码为:
func main() {
r := mux.NewRouter()
r.HandleFunc("/echo", echoHandler).Methods("POST", "OPTIONS")
headers := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
origins := handlers.AllowedOrigins([]string{"*"})
methods := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
http.Handle("/", r)
port := 10080
if portStr := os.Getenv("PORT"); portStr != "" {
port, _ = strconv.Atoi(portStr)
}
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), handlers.CORS(headers, origins, methods)(r)))
}
func echoHandler(w http.ResponseWriter, r *http.Request) {
// echoHandler reads a JSON object from the body, and writes it back out.
var msg interface{}
if err := json.NewDecoder(r.Body).Decode(&msg); err != nil {
if _, ok := err.(*json.SyntaxError); ok {
errorf(w, http.StatusBadRequest, "Body was not valid JSON: %v", err)
return
}
errorf(w, http.StatusInternalServerError, "Could not get body: %v", err)
return
}
b, err := json.Marshal(msg)
if err != nil {
errorf(w, http.StatusInternalServerError, "Could not marshal JSON: %v", err)
return
}
w.Write(b)
}我的app.yaml是:
# [START swagger]
swagger: "2.0"
info:
description: "My API"
title: "My API"
version: "1.0.0"
host: "my.api"
x-google-endpoints:
- name: "my.api"
target: "X.X.X.X"
allowCors: "true"
# [END swagger]
basePath: "/"
consumes:
- "application/json"
produces:
- "application/json"
schemes:
- "https"
paths:
"/echo":
post:
description: "Echo back a given message."
operationId: "echo"
produces:
- "application/json"
responses:
200:
description: "Echo"
schema:
$ref: "#/definitions/echoMessage"
parameters:
- description: "Message to echo"
in: body
name: message
required: true
schema:
$ref: "#/definitions/echoMessage"
definitions:
echoMessage:
properties:
message:
type: "string"
searchMessage:
properties:
message:
type: "string"发布于 2018-02-08 23:49:00
您将收到403错误,这意味着您的印前检查请求缺少通过访问控制检查的适当身份验证。
在这种情况下,请求要发往的资源的CORS配置应该包含Access-Control-Allow-Origin标头。此标头应包含允许访问资源的所有HTTP源。
以防万一,您应该添加一个或多个Access-Control-Request-Header标头,其值必须与CORS配置中的ResponseHeader值匹配。在CORS配置中,Access-Control-Request-Header中的所有报头都应该出现在Access-Control-Allow-Origin报头中,这样才能授权请求。
您可以找到有关正确的身份验证here的更多信息。
https://stackoverflow.com/questions/48466261
复制相似问题