duanmin0941 2018-03-18 17:08
浏览 245

对预检请求的响应未通过访问控制检查:“ Access-

I have created an API using Go. It's working fine in postman but not when consumed using javascript. When I post request using javascript I'm getting an error saying that Access-Control-Allow-Origin is set to null.

go API code:

package main

import (
    "fmt"
    "encoding/json"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

type Calculate struct {
    Operand1  string   `json:"Operand1,omitempty"`
    Operand2 string   `json:"Operand2,omitempty"`
    Operator  string   `json:"Operator,omitempty"`
}

type Answer struct {
    Res string  `json:"Res,omitempty"`
}


func do_Calculation(w http.ResponseWriter, r *http.Request) {
    var cal Calculate
    var ans Answer
    fmt.Println("Request Reached")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.WriteHeader(http.StatusOK)
    json.NewDecoder(r.Body).Decode(&cal)
    // my stuff
    // res := do_Operations(convertToFloat(cal.Operand1),convertToFloat(cal.Operand2),cal.Operator)
    // ans = Answer{Res: floattostrwithprec(res, 4)}
    json.NewEncoder(w).Encode(ans)
}



// main function to boot up everything
func main() {
    router := mux.NewRouter()
    router.HandleFunc("/calculate", do_Calculation).Methods("POST")
    fmt.Println("Server online at port :8000")
    log.Fatal(http.ListenAndServe(":8000", router))
}

javascript code:

var data = JSON.stringify({
  "Operand1": "2.6",
  "Operand2": "2.4",
  "Operator": "+"
});

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://localhost:8000/calculate");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Methods", "POST");
xhr.withCredentials = true;
xhr.send(data);

error:

Failed to load http://127.0.0.1:8000/calculate: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'null' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

  • 写回答

2条回答 默认 最新

  • duanhuang1699 2018-03-18 17:37
    关注

    Whenever you are setting xhr request with credentials to true. It is a security loop hole to allow cross origin request for all domains using wild card *. So add http://localhost:8000/ to the Access-Control-Allow-Origin.

    var xhr = new XMLHttpRequest();
    
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        console.log(this.responseText);
      }
    });
    
    xhr.open("POST", "http://localhost:8000/calculate");
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Cache-Control", "no-cache");
    xhr.setRequestHeader("Access-Control-Allow-Origin", "http://localhost:8000");
    xhr.setRequestHeader("Access-Control-Allow-Methods", "POST");
    xhr.withCredentials = true;
    xhr.send(data);
    

    Also in header in go lang code allow for http://localhost:8000:

    func do_Calculation(w http.ResponseWriter, r *http.Request) {
        var cal Calculate
        var ans Answer
        fmt.Println("Request Reached")
        w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
        w.Header().Set("Access-Control-Allow-Origin", "http://localhost:8000")
        w.WriteHeader(http.StatusOK)
        json.NewDecoder(r.Body).Decode(&cal)
        // my stuff
        // res := do_Operations(convertToFloat(cal.Operand1),convertToFloat(cal.Operand2),cal.Operator)
        // ans = Answer{Res: floattostrwithprec(res, 4)}
        json.NewEncoder(w).Encode(ans)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数