useSWR 未加载数据。数据保持加载状态

Data is not loading by useSWR. The data remains in loading state

今天,我正在使用 useSWR(zeit) hook for the first time, and I faced an issue that useSWR doesn't return data after fetching. I uploaded my front-end code on git. My express server is running on http://34.66.137.51:4000。您可以通过在端点“/”和“/testing”上请求来验证它。代码如下

const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');

const app=express();
app.use(cors())
app.use(bodyParser.json());

app.get('/testing',(req,res)=>{
    console.log('testing')
    res.status(200).json([{"nod":"hello"}, {"next":"hello1"}])
})

app.get('/',(req,res)=>{
    console.log('asd')
    res.status(200).json('welcome');
});

app.listen(4000,()=>{
    console.log("listening on 4000")
})

我向您保证 fetch 函数正确调用服务器,因为服务器控制台显示 testing 作为输出。我想知道我做错了什么以及如何解决它以便 data 得到快递服务器的响应。

PS-如果您在理解问题时遇到任何问题,请告诉我。

编辑 1 - 感谢 Santiago Ignacio Poli。他在评论中评论了一个非常有效的解决方案。我只是在这里引用它,以便您轻松阅读。

The above code didn't work because you weren't wrapping your fetch code inside a function, so the code got executed immediately i.e () => fetch(...)

旧解

我认为只有少数开发者使用useSWR,或者我的问题不是很清楚。不管怎样,让我们​​来解决问题。

useSWR App.js

的一部分
const {data, error} = useSWR('http://34.66.137.51:4000/testing',fetch('http://34.66.137.51:4000/testing',{
method:'GET',
header:{ "Content-Type" : "applicaton/json"}
})
.then(response=>response.json())

);

我将 App.js 更改如下。

  const {data, error} = useSWR('http://34.66.137.51:4000/testing',fetcher);

并制作fetcher.js如下

function fetcher(url) {
 return fetch(url, {
  headers: {
   Authorization: `Bearer ${localStorage.getItem('token')}`,
   'Content-Type': 'application/json',
  },
 }).then(response => response.json());
}

export default fetcher;

通过如上所述更改文件,我解决了我的问题。我不知道它为什么有效或为什么无效!如果有人知道,那就去做吧。谢谢。