简体   繁体   English

React js 的 Axios 问题(每次运行 get/put 请求时都会出错)

[英]Axios Issue with React js ( having an error every time I run get/put request )

I am writing in my VSC editor and using React js library and using Axios for my API.我在我的 VSC 编辑器中编写代码并使用 React js 库并为我的 API 使用 Axios。 For this mission, I used a functional component and also a function component.对于这个任务,我使用了一个功能组件和一个功能组件。

Home.js主页.js

import React from 'react'
import { Link } from "react-router-dom";
import './Home.css'
import Courses from './Courses';
import SearchBar from '../components/SearchBar';
import Title from '../components/Title';
import axios from 'axios';
export default function Home() {
const reqBody = {
name:"Roee",
idNumber:"132456789",
idNumberConf:"132456789",
personalNumber:"1234567",
personalNumberConf:"1234567",
hogerNumber:"12345678",
hogerNumberConf:"12345678",
phoneNumber:"054838350",
birthDate:"06/12/1990",
password:"1132456",
passwordConf:"1132456"};

const config = {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
};

const reqFunc = async () => {
    console.log("ddd");
    axios.get('localhost:3010/accounts/mine', reqBody, config).then((res) => {
    console.log("RESPONSE RECEIVED: ", res);
    })
    .catch((err) => {
    console.log("AXIOS ERROR: ", err);
    })


}

      return (
    <>
        <div className="bg"></div>
        <Title title={"Search for Course"}/>
        <SearchBar/>
        {reqFunc()} 
        <Courses/>
        </>
);
}

App.js应用程序.js

import React from 'react';
import { BrowserRouter as Router, Route,Switch} from "react-router-dom";
import { Link } from "react-router-dom";
import Home from './pages/Home';
import Courses from './pages/Courses'
import Navbar from './components/Navbar'
import Signin from './pages/Sign-in'
import Register from './pages/Register'
import ErrorPage from './components/ErrorPage'
import SingleCourse from './pages/SingleCourse'
import './App.css'
import {
  MDBContainer,
} from 'mdbreact';
import Footer from './components/Footer'
function App() {
  return (
      <>

  <Navbar/>
  <MDBContainer fluid>      
  <Switch>

    <Route exact path="/" component={Home}/>
    <Route exact path="/courses" component={Courses}/>
    <Route exact path="/courses/:id" component={SingleCourse}/>
    <Route path="/log-in" component={Signin}/>
    <Route path="/register" component={Register}/>
    <Route component={ErrorPage}/>
  </Switch>

  </MDBContainer>
  <Footer/>
  </>


);
}

export default App;

I got an Error:我有一个错误:

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

in Home (created by Context.Consumer)
in Route (at App.js:24)
in Switch (at App.js:22)
in div (created by Container)
in Container (at App.js:21)
in App (at src/index.js:12)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:11)

Also the err log to the console还有错误日志到控制台

Home.js:36 AXIOS ERROR:  Error: Network Error
at createError (createError.js:17)
at XMLHttpRequest.handleError (xhr.js:80)
at dispatchXhrRequest (xhr.js:166)
at new Promise (<anonymous>)
at xhrAdapter (xhr.js:16)
at dispatchRequest (dispatchRequest.js:49)

What I am doing wrong?!我做错了什么?! Another easy question -> Why this err log print to the console twice?另一个简单的问题 -> 为什么这个 err 日志会两次打印到控制台? How and Why React doing it? React 如何以及为什么这样做?

Try:尝试:

const reqFunc = async () => {
  try {
    const response = await axios.get(
      "localhost:3010/accounts/mine",
      reqBody,
      config
    );
    console.log(response);
  } catch (err) {
    console.log(err);
  }
};

You're not 'await'ing anything in your async function, so the async part is redundant in your example.您没有在异步函数中“等待”任何内容,因此在您的示例中异步部分是多余的。

The first error is because your promise hasn't fully resolved.第一个错误是因为您的承诺尚未完全解决。

I'm not sure I can answer your questions but I have a few comments.我不确定我能回答你的问题,但我有几点意见。 I'm working more with fetch API and my comments work with fetch API so here also can be useful regarding that axios and fetch are similar.我更多地使用 fetch API,我的评论与 fetch API 一起使用,因此这里对于 axios 和 fetch 相似也很有用。 This is not in a valid JSON format: const reqBody I would write like this:这不是有效的 JSON 格式: const reqBody我会这样写:

const reqBody = {
"name":"Roee",
"idNumber":"132456789",
"idNumberConf":"132456789",
"personalNumber":"1234567",
"personalNumberConf":"1234567",
"hogerNumber":"12345678",
"hogerNumberConf":"12345678",
"phoneNumber":"0548336350",
"birthDate":"06/12/1990",
"password":"1132456",
"passwordConf":"1132456"}

HTTP Get request should not take a request body or it is a typo and you meant POST request : HTTP Get 请求不应采用请求正文,否则它是一个错字,您的意思是 POST 请求:

axios.post('localhost:3010/accounts/mine', reqBody, config)

and I would say for the content type can be application/json :我会说内容类型可以是 application/json :

const config = {
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
};

Wrap your call in a useEffect hook and try this:将您的调用包装在useEffect钩子中并尝试以下操作:

  const [data, updateData] = useState(undefined);

  useEffect(() => {
    async function fetchData() {
      const response = await axios.get('localhost:3010/accounts/mine', reqBody, config);
      const json = await response.json();
      updateData(json);
    }
    fetchData();
  }, []);

The problem in your case is that you are calling your fetch code inside the render return statment.您的情况的问题是您在渲染返回语句中调用提取代码。 Try to call the function before you return.尝试在返回之前调用该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM