【问题标题】:React keeps catching Network Error! when trying to get data from localhost:8080React 不断捕获网络错误!尝试从 localhost:8080 获取数据时
【发布时间】:2018-03-23 22:54:35
【问题描述】:

我有一个监听 8080 端口的 golang 服务器。我正在尝试从中获取数据(curl 确实成功获取了它)但是我的 React 应用程序不断在 Axios Get 上捕获错误,它显示“网络错误!”。 我尝试“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)))
}

【问题讨论】:

    标签: reactjs go axios


    【解决方案1】:

    试试 Axios 获取没有 https 的 localhost,像这样axios.get("http://localhost:8080/data")

    要配置golang https服务器需要使用http.ListenAndServeTLS,在你的情况下它是通过这个http.ListenAndServe配置为http的。

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

    【讨论】:

    • Further reading 为 OP。
    • 提供更多上下文:httpshttp 是不同(但相关)的协议。 http 是明文,如果您运行像 Wireshark 这样的网络嗅探器,您实际上可以读取您正在发送的消息。 https 将 http 消息与称为 tls 的加密协议结合在一起。 tlshttps 要求您创建安全对象(私钥、公共证书)才能使其工作。如果您在发送这些消息时查看 Wireshark,您将无法阅读它们。
    • 其实这是一个错字。我仍然不知道为什么我在我的网址中写了“https”,但感谢您指出。
    猜你喜欢
    • 2020-08-05
    • 1970-01-01
    • 2021-08-25
    • 2019-01-13
    • 2022-10-23
    • 2013-06-05
    • 2021-04-25
    • 2019-09-04
    • 1970-01-01
    相关资源
    最近更新 更多