首页 文章

React一直在捕捉网络错误!当试图从localhost获取数据时:8080

提问于
浏览
0

我有一个golang服务器侦听端口8080.我正在尝试从它获取数据(curl确实成功)但我的React应用程序在Axios Get上持续捕获错误,它显示"Network Error!" . 我尝试"rejectUnauthorized: false"忽略SSL错误,我在服务器上尝试了"AllowedOrigins: []string{" http://localhost:3000 "},"以允许来自我的React应用程序的请求 . 我仍然收到错误,Firefox网络选项卡显示:"ssl_error_rx_record_too_long" .

我的React代码如下所示:

//Action creators
 export const fetchDataRequest = () => ({
      type: FETCH_REQUEST
 });

 export const fetchDataSuccess = (elements) => ({
       type: FETCH_SUCCESS,
       payload: {elements}
 });

 export const fetchDataError = (error) => ({
       type: FETCH_ERROR,
       payload: {error}
 });

 export function fetchDataWithRedux() {
       return function (dispatch) {
         dispatch(fetchDataRequest());
         axios.get("https://localhost:8080/data")
      .then((response) =>{
         dispatch(fetchDataSuccess(response.json));
          console.log(response);
       })
      .catch (error => {
           dispatch(fetchDataError(error))
           console.log(error.message);
       })
     }
  }

我的Main.go看起来像这样:

func main() {
    //Call the NewRouter function defined in route pkg
    route := n.NewRouter()

    //convert h.handlers to a http.HandlerFunc
    JSONHandler := http.HandlerFunc(h.JsonHandler)
    DATAHandler := http.HandlerFunc(h.NixDataHandler)

    //Give the handle to the created router
    http.Handle("/", route)
    route.Handle("/nix", h.JsonHandlerWrapper(JSONHandler))
    route.Handle("/data", h.JsonHandlerWrapper(DATAHandler))

    //Call function to fetch data from nix.org periodically
    timer := time.NewTimer(time.Second)
    go func() {
        <- timer.C
        //call function
        data.GetNixData()
    }()

    //Handling CORS requests
    c := cors.New(cors.Options{
        AllowedOrigins: []string{"http://localhost:3000"},
        AllowedMethods: []string{"GET", "POST"},
    })

    //Start listening on port 8080
    log.Fatal(http.ListenAndServe(":8080", c.Handler(route)))
}

1 回答

  • 1

    尝试Axios获取localhost而不使用https,例如 axios.get("http://localhost:8080/data") .

    要配置golang https服务器,需要使用 http.ListenAndServeTLS ,在这种情况下,它由 http.ListenAndServe 配置为http .

    看看官方文档https://golang.org/pkg/net/http/#ListenAndServeTLS

相关问题