如何使用角度

时间:2017-10-02 10:42:54

标签: javascript python angular ionic-framework

我正在使用ionic后端构建django rest framework应用,并且我无法进行简单的http基本身份验证。

后端view

class GetActive(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        settings = Setting.objects.filter(active=True)
        for setting in reversed(settings):
            headers = {'Access-Control-Allow-Origin': '*'}
            return Response({
                'youtube_link': setting.youtube_link,
                'text': setting.text}, headers=headers)
        return HttpResponse('not found')

前端api.ts

@Injectable()
export class ApiProvider {
  url;

  constructor(public http: Http) {
    this.url = 'http://127.0.0.1:8000/get_active/';
  }

  getSettings() {
    var auth = window.btoa("foo:bar"),
        headers = {"Authorization": "Basic " + auth};
    return this.http.get(this.url, {headers: headers}).map(res => res.json());
  }
}

我收到此错误:

403 forbidden No 'Access-Control-Allow-Origin' header is present on the requested resource.

但是,如果我在后端删除IsAuthenticated权限并从前端请求中删除标题,那么它就可以正常工作。

确信在IsAuthenticated打开时确实有效,我制作了这个python脚本:

import requests
from requests.auth import HTTPBasicAuth

theurl = 'http://localhost:8000/get_active'
username = 'foo'
password = 'bar'

r = requests.get(theurl, auth=HTTPBasicAuth(username, password))
print (r.text)

它工作正常,所以我只需要js analog。

1 个答案:

答案 0 :(得分:1)

将CORS添加到服务器。 pip install django-cors-headers并添加标头 也许这个帮助