我正在尝试使用 axios 从我的后端获取数据,但它显示网络错误

I am trying to get data from my backend using axios, but its showing Network error

我有客户端文件夹,其中包含我的反应代码和服务器文件夹,其中包含我的 expressjs 文件。我正在尝试使用 axios 从我支持的 api 获取数据,但出现“网络错误”。服务端和客户端都是运行

server.js

const express = require("express");
const mongoose = require("mongoose");

const app = express();
app.use(express.json({extended:true}));
app.use(express.urlencoded({extended:true}));

const url = "mongodb+srv://pekele:pekele@cluster0.yqaef.mongodb.net/myDatabase?retryWrites=true&w=majority";
mongoose.connect(url)
.then(()=>console.log("connected to database successfully"))
.catch(err=>console.log(err));

app.get("/",(req,res)=> {
    res.send("<h1>Welcome Guest</h1>");
});

app.get("/signup",(req,res)=> {
    res.json({"id":"1"});
})

app.listen(5000,()=> console.log("Server listening on port 5000"));

下面是我的反应组件的代码

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

const Registration = () => {

const [user,setUser] = useState({email:"",password:""});

const handleSubmit = (e) => {
    e.preventDefault();
    console.log(user);

   

    axios.get('http://localhost:5000/signup')
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
          console.log("error here")
        console.log(error.message);
      });
}


    return (
        <div>
            <h1>Registration</h1>
            <form onSubmit={handleSubmit}>
                <div>Email:</div> 
                <div><input type="text" name="email" placeholder='Enter your email' 
                    onChange={(e)=>setUser({...user,email:e.target.value})}
                /></div>
                <div>Password:</div> 
                <div><input type="password" name="password" placeholder='Enter your password'
                    onChange={(e)=>setUser({...user,password:e.target.value})}
                    /></div>
                <div><input type="submit" value="Add" /></div>
            </form>
        </div>
    )
}

export default Registration;

你在使用 cors

尝试将此添加到您的服务器端代码

const cors = require('cors');

app.use(cors({origin: true, credentials: true}));