如何解决CORS策略已阻止从来源“ http:// localhost:3000”访问“ http:// localhost:8000 / api / puppies”处的抓取
我想使用Laravel从后端在我的Reacjs应用程序中获取列表。当我在Reactjs组件中调用Api时,它给了我这个错误消息
**访问CORS策略已阻止从源“ http:// localhost:3000”获取“ http:// localhost:8000 / api / puppies”的访问:“ Access-Control-Allow-Origin”标头包含多个值“ ,”,但只允许一个。让服务器发送带有有效值的标头,或者,如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。
cors中间件
<?PHP
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request,Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin',"*")
->header('Access-Control-Allow-Methods',"PUT,POST,DELETE,GET,OPTIONS")
->header('Access-Control-Allow-Headers',"Accept,Authorization,Content-Type");
}
}
我的API路由
Route::apiResource('puppies','Api\PuppiesController');
前端代码
我的卡片js API
import React,{useState,useEffect} from 'react';
import {Link} from 'react-router-dom';
import {getPuppies} from "./apiCore";
const Card = () => {
const [allPets,setAllPets] = useState([]);
const loadAllPets = () => {
getPuppies().then(data => {
if(data.error){
console.log(data.error)
} else{
setAllPets(data)
}
});
};
useEffect(() =>{
loadAllPets();
},[])
return(
<div>
<div className="row">
<div className="col-lg-4 col-md-6 col-12">
{/* <div className="listing-block">
<div className="listing-image">
<img src="img/listing.jpg" alt="safari"/>
</div>
<div className="listing-content">
<div className="tag ondeposite">ON Deposite</div>
<h3>Golden Retriver</h3>
<h4>Poodele,4 Weeks</h4>
<Link to="/description" className="Boxed-btn3">View puppy</Link>
</div>
</div> */}
{JSON.stringify(allPets)}
</div>
</div>
</div>
)
}
export default Card;
API
import {API} from "../config";
export const getPuppies = () =>{
const url = "http://localhost:8000/api/puppies"
return fetch(url,{
method: "GET",})
.then(response =>{
return response.json();
})
.catch(err =>{
console.log(err);
});
};
解决方法
我认为您可以在浏览器中安装此扩展程序:
Extension : Allow CORS: Access-Control-Allow-Origin
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。