'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource - reactjs

I am working on project using Django and React using Rest Framework. I have set CORS_ALLOW_ALL_ORIGINS=True in settings.py still i am getting error Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/encrypt/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am using axios to post and get request. Suprisingly even after error post request is made but get request fails.
This is react file using axios
sendImage =()=> {
this.activateSpinner()
let formData = new FormData()
formData.append('to_be_hidden', this.state.files[0], this.state.files[0].name)
formData.append('used_to_hide', this.state.files[1], this.state.files[1].name)
axios.post('http://127.0.0.1:8000/api/encrypt/', formData, {
headers: {
'accept': 'application/json',
'content-type': 'multipart/form-data'
}
})
.then(resp=>{
this.getImageClass(resp)
console.log(resp.data.id)
})
.catch(err=>{
console.log("Code broke at send image")
console.log(err)
})
}
getImageClass =(obj)=> {
axios.get(`http://127.0.0.1:8000/api/encrypt/${obj.data.id}/`, {
headers: {
'accept': 'application/json',
}
})
.then(resp=>{
this.setState({recentImage:resp})
console.log(resp)
})
.catch(err=>{
console.log("Code broke at get image")
console.log(err)
})
this.deactivateSpinner()
}

ALLOWED_HOSTS=['*']
INSTALLED_APPS = [
'django.contrib.admin',
...
'corsheaders',
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
....
"corsheaders.middleware.CorsMiddleware",
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = [
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
]
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]

It's definitely the issue from the backend side, I mean Django.
CORS_ALLOW_ALL_ORIGINS=True Once you set the CORS_ALLOW_ALL_ORIGINS value, you also need to set the values for ALLOWED_HOSTS.
For instance
ALLOWED_HOSTS=['*']
Please take a look at the below links.
https://pypi.org/project/django-cors-headers/
https://dzone.com/articles/how-to-fix-django-cors-error

Related

Access to fetch at 'my-url' from origin 'http://www.mywebsite.com' has been blocked by CORS policy

I am getting the cors policy error like this.
Access to fetch at 'my-url' from origin 'http://www.mywebsite.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This is my code:
const requestOptionsBR = {
method: "POST",
headers: new Headers({
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
}),
body: JSON.stringify({
action: "user_reports",
user_id: this.state.user_id,
start_date: this.convertDate(this.state.startDate),
end_date: this.convertDate(this.state.endDate),
}),
};
fetch(my-url, requestOptionsBR)
.then((res) => res.json())
.then((data) => {
this.setState({ loadingStatus: true });
console.log("User Reports", data)
if (data.status) {
this.setState({
user_data: data.params,
loadingStatus: false,
resultRetrieved: true,
});
this.generate_download_csv_data(data.params);
}
The above is working fine in local , but in production it is not working.
How to overcome this issue?
Any help would be great.
The wildcard * isn't allowed, as you must give a specific protocol, domain and port for security reasons.
More info here...
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
As the error message suggests, you can also set the option:
mode: 'no-cors'
...in your requestOptionsBR, however this will limit what you can put in your request headers.
More info here...
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options

'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin'

Can you help me, i have a function problematic:
http://localhost:3000 has been blocked by CORS policy: No Access-Control-Allow-Origin header is present on the requested resource. If an opaque response serves your needs, set the request's mode to no-cors to fetch the resource:
handleSubmit = e => {
e.preventDefault();
const data={
'username' : this.username,
'password' : this.password
}
fetch(process.env.REACT_APP_API_URL+'/api/login', data,{
method:"POST",
headers:{
'accept': 'application/json',
'Access-Control-Allow-Origin': "*",
'content-type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': 'true',
}
})
.then(r => r.json());
}
but there is a problem with the url, how do is solve it?
enter image description here
You can't access resources when the origin you are accessing to is not the same as the origin you are using.
Fixes
As commented by #Freestyle09, you need to enable CORS policies in your backend:
In PHP:
header('Access-Control-Allow-Origin: *');
In node.js (Express):
Install cors package from npm.
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
This should set the headers to Access-Control-Allow-Origin: *, if you want to specify a host:
app.use(cors({
origin: 'http://yourapp.com'
}))
Read more from this answer:
https://stackoverflow.com/a/7564919/11555297
https://medium.com/zero-equals-false/using-cors-in-express-cac7e29b005b
Thank you all for your input and answers, this problem has been resolved, and it's running.
this problem is simple, I just add it in pckage.json
"proxy":"http://127.0.0.1:8000",
and i am use in axios fatch
axios({
url:'/api/login',
data:data,
method:"POST",
mode: 'no-cors',
headers:{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": process.env.REACT_APP_API_URL,
"Access-Control-Request-Headers": 'Content-Type, Authorization'
}
})
.then(res => {
console.log(res);
})
.catch(err =>{
console.log(err);
})
and it's work for me thank you all (n_n)
In spring boot you can use annotation "#CrossOrigin". You will pass the url of your react app for parameter origins:
#CrossOrigin(origins = "http://localhost:3000",methods = RequestMethod.GET)
#GetMapping("/courses")
public Iterable<Course> getCourses() {
CourseService courseService=new CourseService();
return courseService.getAllCourses();
}

CORS: Response to preflight request doesn't pass access control check ( axios )

I'm building a SPA with Reactjs and laravel as API. I use axios to make API calls, some requests work without any issue, however on some pages when I make a request i'll receive a error that the the request is blocked by the CORS policy.
In laravel i'm using the spatie/laravel-cors package to add CORS headers so the preflight requests won't get blocked, by default it will allow any type of request from any origin.
Request:
componentDidMount() {
const url = BACKEND_URL+API+'/XXX/';
let headers = {
"Authorization": "Bearer " + token,
"Content-Type": "application/json",
"Accept": "application/json",
}
axios({
url: url,
method: "GET",
headers: headers,
credentials: 'same-origin',
})
.then(response => {
const data = response.data.data;
this.setState({
data: data,
loading: false
})
})
.catch(error => {
console.log(error);
});
}
Expected response ( from localhost )
{
campaign_id: XXX
category: []
form_entry: {id: XXX, form_id: XXX, lead_id: XXX, fields: Array(1)}
form_entry_id: XXX
id: XXX
landing__page_id: XXX
last_contacted: "XXX"
name: "XXX"
notes: XXX
status: [{…}]
tag: []
}
Error message:
Access to XMLHttpRequest at 'XXX.XXX' from origin 'XXX.XXX' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
from localhost everything works fine with the same setup, the strange thing is that i'm only getting the errors once I put both front and backend online.
Anyone has a clue why this is happening?

What is the best way to enable CORS in React Application?

There are different ways to make a REST call in react-
e.g
axios.post('link', JSON.stringify(data1),
{
headers: {"content-type" : "application/json", "Access-Control-Allow-Origin" : "*"}})
.then(response => {
console.log("res:", response)
})
.catch(err =>{
console.log(err)
})
}
OR
fetch('http://localhost:8080/feedbacks/addfeedback', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
body:body
What is the most effiecient way to enable CORS.
Is there any other way that I can do this either in frontend or backend?
It depends on what HTTP library you are using.
See What is difference between Axios and Fetch?.
I usually use Axios, next what i do is creating a global instance and configuring Axios once.
export const api = axios.create({
baseURL: '_URL_',
timeout: 1000,
withCredentials: false,
responseType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' // whatever you want
}
});
// You can add common headers later
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
Also i'm enabling CORS on my server side application.
Thanks to #henrik123 for good explanation:
The browser is going to see that some Javascript request has tried to initiate a request to a different domain, subdomain or port than what the browsers is currently at. If any of these things are different, the CORS kicks in. Doesn't matter if you use Axios, Fetch or any other other library

How to handle CORS requests in AngularJS

I'm facing problem with CORS requests in AngularJS while calling web services but the same service able to call by using jQuery.
Note: From server side we are receiving header "Access-Control-Allow-Origin:*" and these services are running fine in jQuery application.
Here I'm posting my AngularJS code as well as jQuery code.
AngularJS:
$http({
method: 'POST',
url: $rootScope.host + "UserLogin",
//headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: {
"uname": $scope.uname,
"password": $scope.password
},
}).then(function (success) {
$scope.loginDetails = success;
console.log($scope.loginDetails);
}),function (error){
console.log(error);
});
If I pass the header like headers: { 'Content-Type': 'application/x-www-form-urlencoded' } able to ping the service but my request is not going in JSON format.
If I change the header to 'Content-Type': 'application/json', getting
XMLHttpRequest cannot load https://XXXX.XXXX.in/XXXXAPI/UserLogin.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://170.11.0.61' is therefore not allowed access.
I don't know what is the reason for this error.
$.ajax({
url: BASE_URL + "UserLogin",
type: "POST",
xhrFields: {withCredentials: true},
data: {
"uname": uname,
"password": password
},
cache: false,
success: function (result, textStatus, request) {
console.log(result);
},
error: function (e) {
console.log("Error in login service call:"+JSON.stringify(e));
}
});
This jQuery is sending my request in the json format.
Try to pass headers like
headers: { 'Content-Type': 'application/json' }

Resources