我对React很新,我正在使用Yii2 API . 我想使用React组件从我的API获取数据 . 我可以使用PostMan明显地获取这些数据 . 当我尝试使用React时,fetch语句不会返回任何数据 . 任何有关这方面的帮助都将是值得欣赏的,因为我已经花了几个试图找出这个bug
这是我的ReactJs组件获取功能
fetchPoll(){
console.log("before json")
fetch(URL_HOME, { method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(json => {
console.log("before json2")
this.setState({pollTrendings:json})
console.log("before json3")
console.log(this.pollTrendings)
})
console.log("endingjson")
}
从我的控制台,我无法获得console.log(“在json2之前”和console.log(“在json3之前”) . 这意味着我的fetch语句不成功 .
以下是我的API endpoints
public static function allowedDomains()
{
return [
'*',
];
}
public function behaviors()
{
return array_merge(parent::behaviors(), [
// For cross-domain AJAX request
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
'cors' => [
// restrict access to domains:
'Origin' => static::allowedDomains(),
'Access-Control-Request-Method' => ['POST'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600, // Cache (seconds)
],
],
]);
}
public function actionTrendingmusic(){
//find all the rows in the trending table with status current and type music
$trending = Trending::find()
->where(['status'=>'current', 'type'=>'music'])
->all();
return $trending;
}