我试图通过构建一个简单的spotify应用程序来学习角度2 .
但不知何故,我陷入了身份验证过程中 .
我的问题是,当我尝试发送 Headers 设置为https://accounts.spotify.com/api/token的http帖子时
let tokenUrl = 'https://accounts.spotify.com/api/token';
let keyEncrypted = btoa( this.client_id + ':' + this.client_secret);
let authHeaders = new Headers();
authHeaders.append('Content-Type', 'application/x-www-form-urlencoded');
authHeaders.append('Authentication', 'Basic ' + keyEncrypted);
let options = new RequestOptions({headers: authHeaders});
let body = 'code=' + authCode + '&grant_type=authorization_code' + '&redirect_uri=' + this.redirect_uri;
let jsonString = JSON.stringify({
code: authCode,
grant_type: 'authorization_code',
redirect_uri: this.redirect_uri
})
return this._http
.post(
tokenUrl,
jsonString,
options
).map( res => {
res.json();
})
我得到一个飞行前的“ Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'... ”
但是当我从返回中删除 Headers 时
return this._http
.post(
tokenUrl,
jsonString // Header removed
).map( res => {
res.json();
})
飞行前检查似乎已被绕过,但后来我得到了媒体类型不允许错误 .
所以我现在感到很困惑,并且想知道:1 . 为什么发送没有邮件 Headers 的邮件会绕过飞行前检查而发送邮件不带 Headers ? 2.当设置标头并且未设置时,angular http post会发送不同类型的请求吗?
非常感谢 .
2 回答
您必须准确了解如何从Spotify获取令牌 . 但是看看你的代码,我可以通过查看Spotify documentation这行来告诉你
应该是
authHeaders.append('Authentication', 'Bearer ' + keyEncrypted);
首先,尝试使用像Postman或Curl这样的程序从Spotify API获取令牌,使用令牌发出请求,然后一旦从API接收数据并且您清楚地了解流程应该如何工作,那么请尝试使用Angular2应用程序 .
Here - text / plain标头不会触发CORS pre-flight . 删除content-type标头将默认为text / plain .
尝试使用Chrome并以不安全模式启动它 - PowerShell中的一个示例就是
& "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\Users\{yourusername}\AppData\Local\Google\Chrome\User Data\Default"