我在我的Django项目中实现了Django Rest框架,这样我就可以使用Django作为我的Ionic Framework应用程序的后端,同时维护我可以用Django制作的web应用程序。我使用oauth工具包访问了OAuth2,但现在我不确定如何从ionic框架端调用http请求来验证用户并获得令牌。到目前为止,在离子方面,我的http请求如下:
login(username, password, url) {
let headers = new Headers()
headers.append("Content-Type", "application/x-www-form-urlencoded");
return this.http.post(url,
{"username": username,
"password": password,
}, {headers: headers})
.map(res => res.json());
}
但当我在浏览器中运行它时,我得到的是No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500.
在服务器端,curl命令curl -X POST -d "grant_type=password&username=USERNAME&password=PASSWORD" -u "CLIENT ID:CLIENT SECRET" https://www.example.com/o/token/
可以很好地工作,并返回一个令牌,其中用户名、密码、客户机ID和客户机秘密都是各自的值。
我不确定这是否是正确的问题,但我如何将cURL命令转换为可以在我的离子应用程序中使用的东西?
以下是我的Rest框架和CORS设置:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated'
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
]
}
CORS_ORIGIN_WHITELIST = [
'localhost:8100',
]
CORS_ALLOW_CREDENTIALS = True
发布于 2017-12-06 04:11:31
因此,如果您发送的请求的来源是localhost
或127.0.0.1
,这是相同的事情,大多数浏览器将来源作为Null
发送,因此最好将CORS_ORIGIN_ALLOW_ALL = True
添加到主Django项目的settings.py
文件中。
在那里,我收到了关于grant_type
无效的错误,所以在我的请求中,我必须添加"grant_type": "password"
,我还必须添加"client_id": <your client id here>
,其中<your client id here>
是您的客户端id,不带<>
。
我还发现Postman是一个很棒的应用程序,可以帮助创建应用程序编程接口,并将cURL命令转换为有效的HTTP请求。
https://stackoverflow.com/questions/47654886
复制相似问题