"Network Error" with Axios and DjangoREST but request succeeds at the end - reactjs

So, I am using ReactJS and DjangoRESTframework to build my app.
Now..when I send a request with Postman it works perfectly(ex. 127.0.0.1:8000/api/users/ GET request) and when I try to do it in React with Axios I get a network error but on my local development server console I see that it succeeded.
This is my get request with axios in react:
componentDidMount() {
axios.get('http://127.0.0.1:8000/api/users/', {
headers: {
'Accept': 'application/json'
}
})
.then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
})
}
And I get an Network Error. But as I said with Postman it works.
One more example is that I send POST request with Axios to http://127.0.0.1:8000/api/users/ and as response I get Network Error as well but on my backend, user IS created.
This is code for my POST request with axios:
let formData = new FormData();
formData.set('email', this.state.emailField);
formData.set('username', this.state.usernameField);
formData.set('password', this.state.passwordField);
axios({
method: 'POST',
data: formData,
url: 'http://127.0.0.1:8000/api/users/',
config: {headers: {'Content-Type': 'multipart/form-data'}}
}).then(request => {
console.log(request.data);
}).catch(err => {
console.log(err);
})
I googled for about an hour to fix this but nothing helps.

Can you be more clear on what you see as Network error? Attach some error messages / Stack trace.
This looks like a Cross-Origin Resource Sharing (CORS)
issue to me. Try configuring CORS on your DjangoRESTframework backend.
This might help you if that is the case.

Related

Axios returns NetworkError / CORS Headers enabled

I build a ionic-react android application with Axios to get a server response. Two weeks ago my code was working fine. Now the axios request always returns a NETWORK_ERR (HttpError or Axios Error).
I tried to use all CORS Headers possible in my api, but the request is not sent to the webservice.
I hope anyone can help me:
This is the Code I was using:
const api = axios.create({
baseURL: "http://192.168.0.145:8080/RestFulTest-1.0-SNAPSHOT/api",
});
function callApi(){
api.get("/verification")
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
}
Just directly opening the API Url in browser is not loading it...
Sot it seems either the backend is down or blocking and requires an authorization header with the axios request, like
let tokenStr = "Your TOKEN";
axios.get("/verification", { headers: {"Authorization" : `Bearer ${tokenStr}`} });
Hope it helps..

Axios post blocked by CORS. Using CLoudinary api

I am trying to do a post request with axios to upload a image to cloudinary from my frontend React app. I am getting this error from the axios code below:
http://localhost:3000 has been blocked by CORS policy: Request header field x-access-token is not allowed by Access-Control-Allow-Headers in preflight response.
Using axios, doesnt work gives me cors error
await axios({
method: "POST",
url: "https://api.cloudinary.com/v1_1/******/image/upload/",
data: {
file: img,
upload_preset: "*****",
cloud_name: "****",
},
})
.then((res) => {
console.log("response");
console.log(res);
})
.catch((err) => console.log(err));
Meanwhile when i use fetch using the same api request, the post request works and doesnt give me error. Anyone know why and how to call the api using axios?
const data = new FormData();
data.append("file", img);
data.append("upload_preset", "*****");
data.append("cloud_name", "*****");
await fetch(
" https://api.cloudinary.com/v1_1/****/image/upload/",
{
method: "post",
body: data,
}
)
.then((resp) => resp.json())
.then((data) => {
setUrlArray((prevState) => [...prevState, data.url]);
})
.catch((err) => console.log(err));
Extra info: My upload preset is unsigned.
Also got this from the console after making the axios api call
{
error: {
message: "Upload preset must be specified when using unsigned upload"
}
}
To create an Axios request equivalent to your working fetch() one, you need to
Craft a FormData instance and set it as the request data so your content-type is multipart/form-data
Make sure you're not using a previously created Axios instance with unwanted default headers
If custom headers have been set on the default Axios instance, eg
axios.defaults.headers.common["x-access-token"] = TOKEN
you may need to override / delete them in transformRequest
To avoid any interceptors defined on the default Axios instance, create a new separate instance for un-intercepted requests
import axios from "axios" // import the default instance
// create a new instance without interceptors.
// you could also create this in its own module and import from there
const instance = axios.create()
const data = new FormData()
data.append("file", img);
data.append("upload_preset", "*****");
data.append("cloud_name", "*****");
const res = await instance.post(
"https://api.cloudinary.com/v1_1/******/image/upload/",
data
)
Ideally, if your app is going to customise requests, you should always use an Axios instance (or multiple instances) to avoid messing around with the defaults.

Getting the React CORS preflight error in React Native

I am getting the CORS access error in my React Native app when connecting to an external API.
async componentDidMount() {
// POST request using fetch with async/await
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: JSON.stringify({ type:'accountLookup',storeId:STORE_ID, storeKey:STORE_KEY, memberId:'471324' })
};
const response = await fetch('http://frequent5.revlogical.com/wsMobile', requestOptions);
const data = await response.json();
this.setState({ data: data });
The problem is most likely not with React app, rather with your server which is not configurated to serve your app.
You should set 'Access-Control-Allow-Origin' header on your server to allow your app's address to make requests.
This problem is usually the fault of the backend. Test it with a tool like https://www.test-cors.org/
An alternative is to create a server to be intercepted between the frontend and the API, and you can handle this guy's cors

Access to fetch at 'blahblahblah' from origin 'http://localhost:3001' has been blocked by CORS policy

i'm trying to fetch an api but i keep encountering the same error over and over, and i have checked the server and there's no problem from there, i was wandering if you can help me with it.
this is the code that i wrote:
import React from 'react';
export default class FetchData extends React.Component {
async componentDidMount() {
var myHeaders = new Headers();
myHeaders.append("Authorization", "sth");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("blahblahblah", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
render() {
return <div>
</div>
}
}
It is solved in several ways:
First -
Your url add this address at the end
https://cors-anywhere.herokuapp.com/YOUR URL
Second -
see this doc Proxying API Requests in Development
Other ways -
3 Ways to Fix the CORS Error — and How the Access-Control-Allow-Origin Header Works
You will need to whitelist your domain inside your server. the easiest way is to use the npm package cors for your cors configuration
have you know what is the meaning CORS ?it means (Cross-Origin Resource Sharing) see this link to understand it [https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS]
your backend must accept CORS and when you send credentials in the request you must allow credentials also

Fetch request to Cloudinary API from with React Component fails

I want to make an HTTP request to the Cloudinary API for pictures in my account. The url necessary looks like this:
https://<<API KEY>>:<<API SECRET>>#api.cloudinary.com/v1_1/<<RESOURCE NAME>>/resources/image
and when I hit this url from the browser, I get what I'm looking for, a beautiful JSON object with all my pictures.
But when I hit the url from within a React component,
componentDidMount() {
this.props.fetchArt();
}
I get the following error:
TypeError: Failed to execute 'fetch' on 'Window': Request
cannot be constructed from a URL that includes credentials:
The action creator looks like
export function fetchArt() {
const url = 'https://'+CLOUDINARY_KEY+':'+CLOUDINARY_SECRET+'#api.cloudinary.com/v1_1/prints20/resources/image';
const request = fetch(url).then(res => res.json())
return {
type: FETCH_ART,
payload: request
}
}
Link to the repo: https://github.com/PantherHawk/prints20-2018
Thanks a million in advance!
If your endpoint requires some sort of authorization you'll need to pass that info inside the headers of your request.
Cloudinary Authentication is done using Basic Authentication over secure HTTP. Your Cloudinary API Key and API Secret are used for the authentication.
fetch('https://api.cloudinary.com/v1_1/CLOUD_NAME/resources/image', {
method: 'get',
headers: {
'Authorization': 'Basic ' + base64.encode(API_KEY + ":" + API_SECRET),
},
}).then(res => res.json())

Resources