简体   繁体   English

没有“访问控制允许来源”?

[英]No 'Access-Control-Allow-Origin"?

I used request in React to get data from api but I'm getting this error :我在 React 中使用 request 从 api 获取数据,但出现此错误:

Failed to load https://xxxx/api/yyyy?results=1000 : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.无法加载https://xxxx/api/yyyy?results=1000 :对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin ' http://localhost:8000 ' is therefore not allowed access.因此,不允许访问 Origin ' http://localhost:8000 '。

I enabled cross-origin resource sharing in my chrome but I face the same error我在我的 chrome 中启用了跨源资源共享,但我遇到了同样的错误

this is the route这是路线

Route::group(['middleware'=>'cors:api'],function(){
Route::get('/xxxx','yyyyController@yyyFunction');
});

and this is the cors middleware这是 cors 中间件

public function handle($request, Closure $next)
   {
       return $next($request)
       ->header('Access-Control-Allow-Origin', '*')
       ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')

       ->header('Access-Control-Allow-Headers', 'Content-Type, Content-Range, Content-Disposition, Content-Description')
       ->header('Connection', 'close')
       ->header('Cache-Control', 'max-age=2592000')
       //->header('Transfer-Encoding', 'chunked')

       ;
   }

If you call an API from browser but this endpoint has not been defined the CORS, Browser will block the request and show the error like in your question.如果您从浏览器调用 API 但此端点尚未定义 CORS,则浏览器将阻止请求并显示与您的问题类似的错误。 You can refer this doc to learn more about CORS您可以参考此文档以了解有关CORS 的更多信息

Try this is work for me.试试这对我有用。

***reactjs use axios *** reactjs 使用 axios

const data = { 'id': 'xx', 'article': 'dd' };
const url = 'http://localhost:8080/path'
const options = {
  method: 'POST',
  data: qs.stringify(data),
  url,
};
axios(options)
  .then(function (response) {
    console.log(response);
  }).catch(function (error) {
    console.log(error);
  });

Hope for help.希望得到帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM