Access to fetch at https://api-test-license.onrender.com/licenses'from origin https://license-frontend.onrender.com has been blocked by CORS policy

huangapple go评论79阅读模式
英文:

Access to fetch at https://api-test-license.onrender.com/licenses'from origin https://license-frontend.onrender.com has been blocked by CORS policy

问题

我正在使用render创建一个简单的全栈应用程序,后端使用Python和Django框架编码,我已经部署了后端和前端,但仍然得到相同的结果,即

从源 'https://license-frontend.onrender.com' 到 'https://api-test-license.onrender.com/licenses' 的跨源请求被阻止:响应到预检请求未通过访问控制检查:不允许对预检请求进行重定向。

这是我的JS代码

const url = 'https://api-test-license.onrender.com/licenses';

export const nuevaLicencia = async license => {

     try {
         await fetch(url, {
             method: 'POST',
             body: JSON.stringify(license),
             headers: {
                 'Content-Type':'application/json'
             }
         });
         window.location.href = 'index.html';
     } catch (error) {
         console.log(error);
     }
 }


 export const obtenerLicencias = async () => {
     try {
         const resultado = await fetch(url);
         const licencias = await resultado.json();
         return licencias;
     } catch (error) {
         console.log(error);
     }
 } 

 export const eliminarLicencia = async id => {
     try {
         await fetch(`${url}/${id}`, {
             method: 'DELETE'
         })
     } catch (error) {
         console.log(error);
     }
 }

 export const obtenerLicencia = async id => {
     try {
         const resultado = await fetch(`${url}/${id}`);
         const licencia = await resultado.json();
         return licencia;
     } catch (error) {
         console.log(error);
     }
 }

 export const actualizarLicencia = async licencia => {
     try {
         await fetch(`${url}/${licencia.id}`, {
             method: 'PUT',
             body: JSON.stringify(licencia),
             headers: {
                 'Content-type' : 'application/json'
             }
         });
         window.location.href = 'index.html';
     } catch (error) {
         console.log(error);
     }
 }

这是我的Django代码在视图文件中

from .models import License
from .serializers import LicenseSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny

@api_view(['GET', 'POST'])
@permission_classes([AllowAny])
def license_list(request, format=None):

     if request.method == 'POST':
         serializer = LicenseSerializer(data=request.data)
         if serializer.is_valid():
             serializer.save()
             return Response(serializer.data, status=status.HTTP_201_CREATED)
         else:    
             return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        
     else: 
         licenses = License.objects.all()
         serializer = LicenseSerializer(licenses, many=True)
         return Response(serializer.data, status=status.HTTP_200_OK)


@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([AllowAny])
def license_detail(request, id, format=None):

     try:
          license_var = License.objects.get(pk=id)
     except License.DoesNotExist:
         return Response(status=status.HTTP_404_NOT_FOUND)
 
     if request.method == 'PUT':
         serializer = LicenseSerializer(license_var, data=request.data)
         if serializer.is_valid():
             serializer.save()
             return Response(serializer.data)
         else:    
             return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
     elif request.method == 'DELETE':
         license_var.delete()
         return Response(status=status.HTTP_204_NO_CONTENT)

     else:
         serializer = LicenseSerializer(license_var)
         return Response(serializer.data, status=status.HTTP_200_OK)

这只是一个简单的CRUD应用程序,但我不明白为什么我会得到相同的错误,我想知道如何解决这个问题,并在以后避免它,因为我对这个还很陌生。

英文:

I'm using render to make a simply fullstack app the back end is coded with python and django framework, i've deployed the back end and front end using render but i'm still getting the same result which is

Access to fetch at 'https://api-test-license.onrender.com/licenses' from origin 'https://license-frontend.onrender.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

this is my JS code

const url = 'https://api-test-license.onrender.com/licenses'
export const nuevaLicencia = async license => {
try {
await fetch(url, {
method: 'POST',
body: JSON.stringify(license),
headers: {
'Content-Type':'application/json'
}
});
window.location.href = 'index.html';
} catch (error) {
console.log(error);
}
}
export const obtenerLicencias = async () => {
try {
const resultado = await fetch(url);
const licencias = await resultado.json();
return licencias;
} catch (error) {
console.log(error);
}
} 
export const eliminarLicencia = async id => {
try {
await fetch(`${url}/${id}`, {
method: 'DELETE'
})
} catch (error) {
console.log(error);
}
}
export const obtenerLicencia = async id => {
try {
const resultado = await fetch(`${url}/${id}`);
const licencia = await resultado.json();
return licencia;
} catch (error) {
console.log(error);
}
}
export const actualizarLicencia = async licencia => {
try {
await fetch(`${url}/${licencia.id}`, {
method: 'PUT',
body: JSON.stringify(licencia),
headers: {
'Content-type' : 'application/json'
}
});
window.location.href = 'index.html';
} catch (error) {
console.log(error);
}
}

and this is my django code in the view file

 from .models import License
from .serializers import LicenseSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
@api_view(['GET', 'POST'])
@permission_classes([AllowAny])
def license_list(request, format=None):
if request.method == 'POST':
serializer = LicenseSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:    
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else: 
licenses = License.objects.all()
serializer = LicenseSerializer(licenses, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([AllowAny])
def license_detail(request, id, format=None):
try:
license_var = License.objects.get(pk=id)
except License.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'PUT':
serializer = LicenseSerializer(license_var, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:    
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
license_var.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
else:
serializer = LicenseSerializer(license_var)
return Response(serializer.data, status=status.HTTP_200_OK)

It's just a simple CRUD app but i don't understand why i'm gettin the same error and i woud like to know how can i solve this and avoid it next time because i'm new with this

答案1

得分: 0

我建议使用 django-cors-headers

https://github.com/adamchainz/django-cors-headers/blob/main/README.rst#setup

完成设置后,您可以按照以下步骤进行操作:

开发模式

# settings.py
CORS_ALLOW_ALL_ORIGINS = True # 添加这行

在线模式

# settings.py
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = [
    'https://license-frontend.onrender.com', # 添加前端域名
    ...
]

请勿在生产环境中启用 CORS_ALLOW_ALL_ORIGINS。

英文:

I recommend using django-cors-headers.

https://github.com/adamchainz/django-cors-headers/blob/main/README.rst#setup

Once you have completed the setup, you can follow the steps below:

development mode

# settings.py
CORS_ALLOW_ALL_ORIGINS = True # add this

online mode

# settings.py
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = [
'https://license-frontend.onrender.com', # add frontend domain
...
]

> Please do not enable CORS_ALLOW_ALL_ORIGINS in production.

答案2

得分: -1

我认为请求被同源策略阻止了。

根据您提供的代码,您从https://license-frontend.onrender.com发起了对https://api-test-license.onrender.com/licenses的请求。


对于https://api-test-license.onrender.com/licenses

协议:https

主机:api-test-license.onrender.com


对于https://license-frontend.onrender.com

协议:https

主机:license-frontend.onrender.com

因此,两者之间的主机是不同的。

英文:

I think the request was blocked by the Same-origin policy

According the code you provided, you fetched at https://api-test-license.onrender.com/licenses from origin https://license-frontend.onrender.com


For https://api-test-license.onrender.com/licenses

Protocol:https

Host:api-test-license.onrender.com


For https://license-frontend.onrender.com

Protocol:https

Host:license-frontend.onrender.com

So the host between the two is different

huangapple
  • 本文由 发表于 2023年7月10日 11:03:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76650449.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定