No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Derooie

I have created an API in Django, and some plain files from the desktop for angular and html. I like to fill an angular app with the API output. The request reaches the webserver, but then i get an error.

I get the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

So i need to add "Access-Control-Allow-Origin" = True or something, but where and how? I have read many issues now, tried different things where and how to add, but i cannot figure it out. Can someone please help me with this? Thanx in advance.

views.py

def myjson(request):
    data = Dish.objects.all()
    #data = {'string':'test', 'twee':'pollo'}
    #data = serializers.serialize('json', data)
    data = json.dumps( [{'name': o.name, 'description': o.description, 'persons': o.persons} for o in data])
    return HttpResponse(json.dumps(data),mimetype="application/json")

script.js

var myApp = angular.module('myApp', []);

myApp.controller('UserCtrl', ['$scope', '$http', function ($scope, $http) {

  $scope.dish = {};

  //$scope.dish = [{"persons": 4, "name": "Pasta Bolognese", "description": "Pasta met een saus op tomaten basis"}, {"persons": 2, "name": "Pasta Carbonara", "description": "gdsdgfgds"}, {"persons": 4, "name": "Pizzadeeg voor Big Green Egg", "description": "sdgfgfdgfd"}, {"persons": 2, "name": "Low and Slow Ribs", "description": "fdsfsdsfdfsddf"}];

  //$scope.dish = '';

  $http({
    method: 'GET',
    url: 'http://127.0.0.1:8000/food/myjson/'
  })
  .success(function (data) {
    // See here, we are now assigning this username
    // to our existing model!
    $scope.dish = data;
  })
  .error(function (data, status, headers, config) {

  });
}]);

html

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-route.js"></script>
<script src="script.js"></script>
<script type="text/javascript">
</script>

</head>

<body>
<div ng-app="myApp">
    <div ng-controller="UserCtrl">

                {{ dish }} 
    </div>
</div>
</body>

</html>
EnigmaRM

This is a CORS (cross-origin resource sharing) issue. It happens when you try to hit an endpoint that is on a different domain. So that'd make sense if you have a REST API for your backend.

Your API needs to set headers to allow requests from various sources. We had to allow Access-Control-Allow-Origin to allow localhost for our dev environments. I found that in Angular, with each request, you need to send withCredentials: true as well.

  $http({withCredentials: true, method: 'GET', url: http://127.0.0.1:8000/food/myjson/' })
  .success(function (data) {
      // See here, we are now assigning this username
      // to our existing model!
      $scope.dish = data;
  })
  .error(function (data, status, headers, config) {

  });

});

Some sources say you also need to set the header on the client side as well for each request. I haven't had to do that though. But it may not hurt to include it:

headers: {'Content-Type': 'application/json; charset=utf-8'}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Spring Boot Security No 'Access-Control-Allow-Origin'header is present on the requested resource error 오류

Angularjs: Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin in chrome

ajax post request is No 'Access-Control-Allow-Origin'header is present on the request resource. '

CORS安全性:将Access-Control-Allow-Origin设置为“ Origin on Request Header”

Can't find origin in Access-Control-Allow-Origin header in Internet Explorer

Access-Control-Allow-Origin OPENCART NO SOLUTION

Valid Access-Control-Allow-Origin responses

Is there a way around Access-Control-Allow-Origin?

Access-Control-Allow-Origin 오류?

Cordova No Access-Control-Allow-Origin

Codeigniter의 Access-Control-Allow-Origin

'Access-Control-Allow-Origin'문제

httpd 중복 Access-Control-Allow-Origin with "Header always set"

No 'Access-Control-Allow-Origin' header error yet the POST goes through anyway

How can I expose the custom header 'Access-Control-Allow-Origin' in WebApi.Cors - 5.2.2

Why isn't Ember.js seeing the Access-Control-Allow-Origin header from my server?

Chrome Origin null은 Access-Control-Allow-Origin에서 허용되지 않습니다.

Cloudfront에서 Access-Control-Allow-Origin 설정

'Access-Control-Allow-Origin'오류 없음

Azure No 'Access-Control-Allow-Origin'헤더

XMLHttpRequest 'Access-Control-Allow-Origin'오류

reactJS에 'Access-Control-Allow-Origin'없음

Firebase 저장소 및 Access-Control-Allow-Origin

S3-Access-Control-Allow-Origin 헤더

Laravel POST 요청 Cors No 'Access-Control-Allow-Origin'

Vue Axios CORS policy: No 'Access-Control-Allow-Origin'

Angularjs post request error No 'Access-Control-Allow-Origin'

symfony2 REST, AngularJs access-Control-Allow-Origin

Angularjs post request error No 'Access-Control-Allow-Origin'

TOP 리스트

  1. 1

    Ionic 2 로더가 적시에 표시되지 않음

  2. 2

    JSoup javax.net.ssl.SSLHandshakeException : <url>과 일치하는 주체 대체 DNS 이름이 없습니다.

  3. 3

    std :: regex의 일관성없는 동작

  4. 4

    Xcode10 유효성 검사 : 이미지에 투명성이 없지만 여전히 수락되지 않습니까?

  5. 5

    java.lang.UnsatisfiedLinkError : 지정된 모듈을 찾을 수 없습니다

  6. 6

    rclone으로 원격 디렉토리의 모든 파일을 삭제하는 방법은 무엇입니까?

  7. 7

    상황에 맞는 메뉴 색상

  8. 8

    SMTPException : 전송 연결에서 데이터를 읽을 수 없음 : net_io_connectionclosed

  9. 9

    정점 셰이더에서 카메라에서 개체까지의 XY 거리

  10. 10

    Windows cmd를 통해 Anaconda 환경에서 Python 스크립트 실행

  11. 11

    다음 컨트롤이 추가되었지만 사용할 수 없습니다.

  12. 12

    C #에서 'System.DBNull'형식의 개체를 'System.String'형식으로 캐스팅 할 수 없습니다.

  13. 13

    JNDI를 사용하여 Spring Boot에서 다중 데이터 소스 구성

  14. 14

    Cassandra에서 버전이 지정된 계층의 효율적인 모델링

  15. 15

    복사 / 붙여 넣기 비활성화

  16. 16

    Android Kotlin은 다른 활동에서 함수를 호출합니다.

  17. 17

    Google Play Console에서 '예기치 않은 오류가 발생했습니다. 나중에 다시 시도해주세요. (7100000)'오류를 수정하는 방법은 무엇입니까?

  18. 18

    SQL Server-현명한 데이터 문제 받기

  19. 19

    Seaborn에서 축 제목 숨기기

  20. 20

    ArrayBufferLike의 typescript 정의의 깊은 의미

  21. 21

    Kubernetes Horizontal Pod Autoscaler (HPA) 테스트

뜨겁다태그

보관