使用fetch时出错:
https://login.microsoftonline.com/common/oauth2/token 400 (Bad Request)
Failed to load https://login.microsoftonline.com/common/oauth2/token:
No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'http://localhost' is therefore
not allowed access. The response had HTTP status code 400. If an opaque response serves
your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Uncaught (in promise) TypeError: Failed to fetch
以下是现有的提取代码:
var formData = {
"client_id": "",
"grant_type": "",
"resource": "https://analysis.windows.net/powerbi/api",
"username": "",
"password": "",
"scope": "openid",
"client_secret": "",
"refresh_token": ""
};
var options = {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: formData,
}
return fetch("https://login.microsoftonline.com/common/oauth2/token", options)
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("Server response wasn't OK");
}
})
.then((json) => {
return json.token;
});
我想使用服务器端PHP请求来避免跨源问题。
PHP的版本是什么?
答案 0 :(得分:0)
关于如何在PHP中使用cURL进行POST,有很多例子。我已经包含了我认为有点直接翻译你的javascript代码。
请注意,我没有对其进行测试,因此无法说明它是否与您的代码完全相同。此外,我不知道返回了什么json字符串,但我也包含了json_decode。但是从那以后你必须自己找出其余部分。
<?PHP
$url = 'https://login.microsoftonline.com/common/oauth2/token';
$fields = array(
'client_id' => '',
'grant_type' => '',
'resource' => urlencode('https://analysis.windows.net/powerbi/api'),
'username' => '',
'password' => '',
'scope' => 'openid',
'client_secret' => '',
'refresh_token' => ''
);
$headers = array(
'Content-Type: application/x-www-form-urlencoded'
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ( $http_status == 200 ) {
$json = json_decode(trim($result));
echo "Token: ".$json->token."\n";
} else {
echo "HTTP Status code: ".$http_status."\n";
echo "Result: ".$result."\n";
}
?>
希望有所帮助
PS。懒惰很好,而且我喜欢copy-gt; pasta和其他人一样多,但你应该只是谷歌前面(字面意思是我做的):)