【问题标题】:React.js fetch method on my api is not working?我的 api 上的 React.js fetch 方法不起作用?
【发布时间】:2021-08-22 02:18:03
【问题描述】:

我正在尝试从托管在本地服务器上的数据库执行简单的 fetch 请求,并且我在后端连接到 mongodb,我的 fetch 方法似乎出了点问题。我加载资源失败:net::ERR_SSL_PROTOCOL_ERROR 和 Uncaught (in promise) TypeError: Failed to fetch

    function App() {


  const [state, setState]= useState({
    track: '',
    artist:'',
    album:'',
    year: 1990
  }
  )

  // const [token, setToken] = useState('');

  useEffect(() => {
   
      
    async function getData(){
      const track = await fetch('https://localhost:3001/api/music')
     .then(res => res.json());
      console.log(track)
      
      setState(track)
      // console.log(res)
    }
getData();

  },[])

also this is my route&controller functions

router.get('/', musicCtrl.index)

controller:

function index(req, res){
    Music.find({}, function(err, music){
        res.status(200).json(music)

    })
}

mongo connection

 const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const musicSchema = new Schema({
    track: String,
    artist: String,
    album: String,
    year: Number

}, {timestamps:true});


module.exports = mongoose.model('Music', musicSchema);

有什么帮助吗?!

【问题讨论】:

  • 你也有错误的路径。 router.get 中的路径是 / 而不是 /api/music ??
  • 我改了,结果还是一样
  • 您正在混合 async 和 await 与 then 和 catch 。使用一个。在 fetch 和 const track 之前删除 await 。您的代码必须只是 fetch().then(res => res.json()).then(track => setTrack(track)) 。正如我在这里提到的,您需要添加 2 个 then 块。
  • 是的,效果不好,它一直告诉我轨道没有定义!!

标签: reactjs mongodb express fetch seeding


【解决方案1】:

您在获取 url 中使用 HTTPS。

改变

const track = await fetch('https://localhost:3001/api/music')

const track = await fetch('http://localhost:3001/api/music')

getData 函数也混合了await.then。将其更改为:-

async function getData(){
  const track = await fetch('https://localhost:3001/api/music')
  console.log(track.json())
  setState(track.json())
}

【讨论】:

  • 谢谢,也改了,但还是不行,出现同样的错误“Uncaught (in promise) TypeError: Failed to fetch”
  • 好的,所以它修复了Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR 错误?另外,你能描述一下抛出错误的地方吗
  • 现在是:GET localhost:3001/api/music net::ERR_EMPTY_RESPONSE at js 26 const track = await fetch('localhost:3001/api/music')
  • also uncaught(in promise) typeerror : failed to fetch at 32 是函数末尾的“}”。我觉得这可能是我为数据库播种的事实,但也许我在后端没有正确引用它。所以我在根目录中创建了一个 seed.js 文件,var MusicData = require('../seed') 我觉得这是错误的我从根目录的文件夹内的文件中要求它
  • 您是否尝试过在浏览器中访问该 URL?由此看来,后端似乎没有响应。
猜你喜欢
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
  • 2017-12-29
  • 2018-05-22
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
相关资源
最近更新 更多