【问题标题】:Issue fetching data with react使用反应获取数据的问题
【发布时间】:2021-07-12 05:55:09
【问题描述】:

我在使用 useEffect 钩子获取数据时遇到了一个罕见的问题......它在 chrome 检查器上给了我“CORS 错误”......这是我的代码:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

import './HomeScreen.css'
import config from '../config'

// Compomnents 
import Quiz from "../components/Quiz";

const HomeScreen = () => {
    const [data, setData] = useState({ quizzes: [] });
    const [loading, setLoading] = useState('true');
    const [error, setError] = useState(false);

    console.log("TESTING...............................");

    useEffect(() => {
        setLoading('testing');

        const url = "https://mocki.io/v1/4a0ad1a9-352a-45bb-84b9-67e6363d6b7a";  //config.prodLocalhostURLRestAPI + 'quizzes';

        fetch(url)
          .then(res => res.json())
          .then(res => {

            setLoading('result..........')

          })
          .catch(error => {
            //console.log(error);
          });


    }, []);
  
    return (
        <div className="homescreen">
            <h2 className="homescreen__title">Quizzes</h2>

            <div className="homescreen__quizzes">
            <h2>{loading}</h2>
            {loading ? <h2>Loading............</h2> : error ? <h2>ERROR</h2> : data.quizzes.map(quiz => (
                <Quiz />
            ))}
            </div>

        </div>
    )
}

export default HomeScreen;

服务器代码是:

var express = require("express"),
    app     = express(),
    http    = require("http"),
    bodyParser  = require("body-parser"),
    methodOverride = require("method-override"),
    server  = http.createServer(app),
    mongoose    = require("mongoose");
    
const port = process.env.OPENSHIFT_NODEJS_PORT || 3011;
app.set('port', port);
app.set('ipaddr', process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1");
app.use(bodyParser.json());
app.use(methodOverride());

//Import routes
const chatsRoutes = require('./routes/quizzes');
    
app.use('/quizzes/', chatsRoutes);

app.get('/', (req, res) => {
    res.send("Ready!");
});
 
/** catch 404 and forward to error handler */
app.use('*', (req, res) => {
  return res.status(404).json({
    success: false,
    message: 'API endpoint doesnt exist'
  })
});


//app.use('/', routesRaids);

mongoose.connect('mongodb://localhost/quizes', {useNewUrlParser: true, useUnifiedTopology: true }, () =>
    console.log('Connected to Mongo DB')
);


app.listen(port);

网址正确,可直接在浏览器上运行。

有什么问题?

【问题讨论】:

  • 关于 CORS 的帖子太多 - 你需要在服务器上修复它
  • 我使用了外部服务器,但仍然发生
  • 那么...该外部服务器是否设置了适当的标头?究竟是什么错误?
  • 错误是:MissingAllowOriginHeader
  • 还有我的其他问题?你认为你设置了正确的标题吗?显示客户端代码是没有意义的,它是相关的服务器代码。

标签: reactjs react-hooks fetch-api


【解决方案1】:

先打npm install cors,然后

var express = require("express"),
    app     = express(),
    http    = require("http"),
    bodyParser  = require("body-parser"),
    methodOverride = require("method-override"),
    server  = http.createServer(app),
    mongoose    = require("mongoose");
const cors = require('cors');
const port = process.env.OPENSHIFT_NODEJS_PORT || 3011;
app.use(cors()) 
app.set('port', port);
app.set('ipaddr', process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1");
app.use(bodyParser.json());
app.use(methodOverride());

//Import routes
const chatsRoutes = require('./routes/quizzes');
    
app.use('/quizzes/', chatsRoutes);

app.get('/', (req, res) => {
    res.send("Ready!");
});
 
/** catch 404 and forward to error handler */
app.use('*', (req, res) => {
  return res.status(404).json({
    success: false,
    message: 'API endpoint doesnt exist'
  })
});


//app.use('/', routesRaids);

mongoose.connect('mongodb://localhost/quizes', {useNewUrlParser: true, useUnifiedTopology: true }, () =>
    console.log('Connected to Mongo DB')
);


app.listen(port);

【讨论】:

  • 现在,我得到了(失败的)net::ERR_CONNECTION_REFUSED。服务器当然启动了
  • @MarcoMartin 请验证您用于从前端调用的 URL 与运行服务器的 URL 相同
  • 我对 url 进行了硬编码,但连接被拒绝...从控制台卷曲到相同的 url 没有问题!
  • 我得到的确切错误是:Typeerror: Failed to fetch
猜你喜欢
  • 2021-11-20
  • 1970-01-01
  • 2022-07-04
  • 1970-01-01
  • 2020-11-15
  • 2020-09-24
  • 2021-02-04
  • 2013-10-08
  • 2020-03-02
相关资源
最近更新 更多