Los*_*les 5 javascript fetch-api
我正在通过 javascript fetch 调用身份验证服务来获取访问令牌。该服务是一个简单的 RESTful 调用。我可以看到使用 fiddler 调用成功(带有 200 响应和 json 数据)。然而,fetch 响应似乎永远不会被调用。下面是一个片段:
const AUTHBODY = `grant_type=password&username=${username}&password=${password}&scope=roles offline_access profile`
const AUTHHEADER = new Headers({'Content-Type': 'application/x-www-form-urlencoded'})
const CONFIG = {
method: 'POST',
headers: AUTHHEADER,
body: AUTHBODY
}
fetch('http://localhost:23461/connect/token', CONFIG).then(function(response) {
console.log('response = ' + response)
return response.json()
}).then(function(json) {
console.log('json data = ' + json)
return json
}).catch(function(error) {
console.log('error = ' + error)
})
Run Code Online (Sandbox Code Playgroud)
当执行上面的 fetch 时,console.logs 都没有被执行......似乎只是挂起。但提琴手另有说法。有任何想法吗?
您可能遇到了 CORS 来源策略问题。为了解决这个问题,您需要一些权限来访问 API 的服务器端。特别是,您需要在 php 或另一个服务器端点的标头中添加一行:
<?php
header('Access-Control-Allow-Origin: *');
//or
header('Access-Control-Allow-Origin: http://example.com');
// Reading JSON POST using PHP
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
// Use $jsonObj
print_r($jsonObj->message);
...
// End php
?>
Run Code Online (Sandbox Code Playgroud)
另外,请确保服务器端点的标头中不包含:
header("Access-Control-Allow-Credentials" : true);
Run Code Online (Sandbox Code Playgroud)
使用 POST 请求的工作获取代码的模型是:
const data = {
message: 'We send a message to the backend with fetch()'
};
const endpoint = 'http://example.com/php/phpGetPost.php';
fetch(endpoint, {
method: 'POST',
body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
console.info('fetch()', response);
return response;
});
Run Code Online (Sandbox Code Playgroud)