I am trying to use axios.post (in TS) to get responses from server (using POST as GET) without sending any Data. The server sends back the Data but REACT cant handle the responses.
Here is the react component:
interface allComapnies {
comapniesData:CompanyData[];
}
function GetAllCompanies(props:allComapnies): JSX.Element {
const myURL = globals.urls.admin "get_company/all";
const [comapniesData,setData] = useState([new CompanyData()]);
useEffect(()=>{axios.post(myURL).then((response)=>{
console.log(response.data);
setData(response.data);
}).catch(error=>{console.log(error)});
},[]);
return (
<div className="getAllCompanies">
{comapniesData.map(item=><OneCompany
key ={item.id}
id={item.id}
name={item.name}
email={item.email}
/>)}
</div>
);
}
export default GetAllCompanies;
The console message shows:
Error: Request failed with status code 302
- at createError (createError.js:16)
- at settle (settle.js:17)
- at XMLHttpRequest.onloadend (xhr.js:54)
The browser get the responses from the server:
[{id: 2, name: "company2", email: "hgfytj@fdgreg", password: "trjyjytk",…},…]
The function of the REST Post inside the Controller in the Server(SPRING):
@RestController
@RequestMapping("admin")
@CrossOrigin(origins = "localhost:3000", allowedHeaders = "*")
@RequiredArgsConstructor
public class AdminController extends ClientController {
private final AdminService adminService;
...
@PostMapping("get_company/all")
public ResponseEntity<?> getAllCompanies() {
return new ResponseEntity<>(adminService.getAllCompanies(), HttpStatus.FOUND);
}
...
}
CodePudding user response:
Try GET method instead POST cause you are getting data from your DB and not sending it to.
CodePudding user response:
You are trying to get the getAllCompanies
from the backend services so you must use the standard GET
method instead of the POST
method.
Getting getAllCompanies
does not need to send extra data. Usually sending token via headers are needed in such cases.
Also, try to call your async Axios function with best practices in useEffect
:
useEffect(() => {
// first define the asyn function
async function getAllCompanies() {
try {
const response = await axios.get(baseUrl "get_company/all")
setData(response.data);
} catch(error) {
// console.log(error)
}
}
// now, call it
getAllCompanies();
},[]);