Home > other >  Spring boot react Uncaught (in promise) Error: Network Error
Spring boot react Uncaught (in promise) Error: Network Error

Time:12-16

i am beginner of connect with api. i want to retrieve data from api http://localhost:8011/getall. i tested through postman it works well.but when i implemented in the react axios data not displayed i checked through the console. error was displayed Uncaught (in promise) Error: Network Error . in order to solve error i added the @CrossOrigin(origins="http://localhost:8010") on Controller but couldn't solve it.

Api Works tested through the brower as well

[{"id":1,"fname":"Raja","lname":"John","city":"Uk","phone":"78899","salary":"30000"},{"id":2,"fname":"Java","lname":"Jsp","city":"Uk","phone":"78899","salary":"30000"}]

what i tried so far i attached below Front End App.js

import axios from 'axios';
import { useState } from 'react';
import './App.css';

function App() 
{
  const myName = "Kobi";

  const [users, setUsers] = useState([]);

 

  async function  handleClick()
  {
     const result = await axios.get(
         "http://localhost:8011/getall"
         );
         setUsers(result.data);
         console.log(result.data);
  }

  return (
    <div className="App">
       <h1>g44</h1>
       <button onClick={handleClick} >Click</button>
       {users.map(function fn(item)
       {
         return  <h1>{item.fname}</h1>;
         
       })}
    </div>
  );
}

export default App;

Student Controller.java

@RestController
@CrossOrigin(origins="http://localhost:8010")
public class StudentController 
{
     @Autowired
     private Studentservice services;
     
     @GetMapping("/getall")
     public Iterable<Student>getStudents() 
     {
         return services.listAll();     
     }
 
     @PostMapping(value = "/save")
     private long saveBook(@RequestBody Student students)   
     {  
         services.saveOrUpdate(students);  
         return  students.getId();  
     }
       
    
     @RequestMapping("/student/{id}")  
     private Student getBooks(@PathVariable(name = "id") int studentid)   
     {  
     return services.getStudentById(studentid);  
     }  
     
        
     @PutMapping("/edit/{id}")
 
        private Student update(@RequestBody Student students)   
        {  
           services.saveOrUpdate(students);  
           return students;  
        }  
 
     @DeleteMapping("/delete/{id}")  
     private void deleteStudent(@PathVariable("id") int id)   
     {  
         services.delete(id);  
     }  
}

CodePudding user response:

Replace "localhost:8010" with "*".

i.e. @CrossOrigin(origins="*")

I believe this should help.

  • Related