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

Time:03-17

I have client folder, containing my react code and server folder containing my expressjs files. I am trying to use axios to get data from my backed api, but I am getting "Network error". Both server and client are running

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:[email protected]/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"));

Then below is the code from my react component

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;

CodePudding user response:

Are you using cors

Try add this to your server side code

const cors = require('cors');

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

  • Related