简体   繁体   English

Laravel和React没有'Access-Control-Allow-Origin'错误

[英]No 'Access-Control-Allow-Origin' error with Laravel and React

I am sending a request from my react app localhost:8080 to my lumen api localhost:8000 to retrieve json data. 我正在从我的React应用程序localhost:8080向我的lumen api localhost:8000发送请求以检索json数据。

This is my routes.php in lumen: $app->get('list', 'ArticleController@listAll'); 这是我的routes.php的流明: $app->get('list', 'ArticleController@listAll');

And this is my ArticleController.php in lumen: 这是我的流明文章ArticleController.php

<?php

namespace App\Http\Controllers;

use Response;
use Illuminate\Support\Facades\Input;
use App\Article as Article;

class ArticleController extends Controller
{
    public function listAll(){
        $articles = Article::all();

        return response()
            ->json($articles)
            ->setCallback(Input::get('callback'));

    }
}

Because I get that error for cross domain fetch, I am trying to use jsonp, but for some reason it's still not working. 因为在跨域获取时遇到该错误,所以我尝试使用jsonp,但是由于某些原因,它仍然无法正常工作。

This is my code in React: 这是我在React中的代码:

componentWillMount(){

    fetch('http://localhost:8000/list?callback=asdf', {
        method: 'GET'
    }).then(function(res) {
        console.log(res);
    }).catch(function(err) {
        console.log(err);
    })
}

Any help would be appreciated. 任何帮助,将不胜感激。 I'm very new to this kind of stuff. 我对这种东西很陌生。 Thanks 谢谢

Problem is that your API server should return correct CORS headers, to allow using it from other domains. 问题是您的API服务器应返回正确的CORS标头,以允许从其他域使用它。

You have two options to solve this: 您可以通过以下两种方法解决此问题:

  1. Add correct CORS in your API responses, there is ready to use solutions like this one https://github.com/barryvdh/laravel-cors or you can even make your own https://gist.github.com/danharper/06d2386f0b826b669552 在您的API响应中添加正确的CORS,可以立即使用像https://github.com/barryvdh/laravel-cors这样的解决方案,或者您甚至可以制作自己的https://gist.github.com/danharper/06d2386f0b826b669552
  2. Use proxy that will add CORS headers (it is possible to add CORS headers to responses using webserver configuration) 使用将添加CORS标头的代理(可以使用Web服务器配置将CORS标头添加到响应中)
  3. Use JSONP 使用JSONP

About JSONP - it is pretty valid option, and it will work... 关于JSONP-这是非常有效的选项,它将正常工作...

But in your case it is not working, because fetch - is not the way you can use it. 但是在您的情况下,它不起作用,因为fetch -不是您使用它的方式。

JSONP is about creating script tag with your request url, and waiting for global callback specified in url to be called when script is loaded( What is JSONP all about? ). JSONP是关于使用您的请求url创建脚本标签,并等待在加载脚本时调用url中指定的全局回调( JSONP的全部含义什么? )。 You need to implement it on your own, or better - use libraries implementing it (for example jQuery) 您需要自己实现,或者更好-使用实现它的库(例如jQuery)

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

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