I am new to this React.js axios concept and when I try to call axios.get, I get AxiosError: Network Error
I'm not sure why this error is coming and I have read this and this some other examples also but I didn't get the proper solution.
And I have install the below two commands
npm install axios
and npm install cors
Below is my code :-
import React from "react";
import { Button } from "@mui/material";
import axios from "axios";
function GetApiData() {
var data = {
vendorname: "achintya",
};
const postData = () => {
axios({
method: "post",
baseURL: "https://somesite.com",
url: "/bkdb_getvendorcodes",
payload: data,
})
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);//showing error here
});
};
return (
<>
<Button variant="outlined" onClick={postData}>POST data</Button>
</>
);
}
export default GetApiData;
When I run the above code I'm getting the below error
But the service is working fine example img
I don't have much knowledge to fix this error please suggest me where I did the mistake and how to achieve this.
Top comments (1)
In Axios, you should use 'data' to send the 'payload', not payload.
In your Express application, require the cors package and use it as middleware before defining your routes. Here's an example of how to configure CORS for your Express app:
This code enables CORS for all routes in your Express application. You can also configure it to allow specific origins, methods, and headers as needed. For example:
Make sure to replace "your-frontend-domain.com" with the actual domain of your React app.
Once you've added this configuration to your Express server, it should send the necessary CORS headers in its responses, allowing your React app to make cross-origin requests to it.