React不断捕获网络错误! 尝试从本地主机获取数据时:8080

React不断捕获网络错误! 尝试从本地主机获取数据时:8080

问题描述:

I have a golang server listening on port 8080. I am trying to get data from it (curl does get it successfully) but my React application keeps catching error on Axios Get, it displays "Network Error!". I tried "rejectUnauthorized: false" to ignore SSL errors, I tried "AllowedOrigins: []string{"http://localhost:3000"}," on my server to allow requests from my React application. I am still getting the error, the Firefox Network tab is showing: "ssl_error_rx_record_too_long".

My React code looks like this:

 //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);
       })
     }
  }

My Main.go looks like this:

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)))
}

Try Axios Get localhost without https, like this axios.get("http://localhost:8080/data").

To configure golang https server need use http.ListenAndServeTLS, in you case it configured for http by this http.ListenAndServe.

Take a look at official docs https://golang.org/pkg/net/http/#ListenAndServeTLS