【问题标题】:Create a custom response from laravel using fetch API使用 fetch API 从 laravel 创建自定义响应
【发布时间】:2016-11-16 02:18:23
【问题描述】:

我目前正在使用以下代码向我的 laravel API 发出POST 请求...

fetch('http://laravel.dev/content', {
        method: 'POST',
        mode:'no-cors',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin':'*'
        },
        body: JSON.stringify({

        })
    })
    .then((response) => {
        console.log(response);
    });

路线如下...

Route::post('/content', array('middleware' => 'cors', 'uses' => 'Test@save'));

虽然我配置了cors模式,但我实际使用的是no-cors

我的控制器Test@save 看起来像...

class Test extends Controller
{

    public function save() 
    {
       echo "here";
    }
}

我正在尝试将字符串 here 发送回获取请求。但是在我的获取请求中,当我执行console.log(response) 时,我得到了以下响应...

Response {type: "opaque", url: "", status: 0, ok: false, statusText: "" ...}

有没有办法使用我的 Laravel 路由发送自定义响应?如果是这样,我该怎么做?

【问题讨论】:

    标签: laravel reactjs fetch


    【解决方案1】:

    你可以试试:

    public function save() 
    {
        return response()->json(['data' => 'here']);
    }
    

    json 方法会自动将Content-Type 标头设置为application/json,并使用 json_encode PHP 函数将给定数组转换为 JSON。

    Docs

    【讨论】:

      【解决方案2】:

      你快到了。您必须返回另一个承诺,从 fetch 中获取文本或 json:

      fetch('http://laravel.dev/content', {
          method: 'POST',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
          },
          body: JSON.stringify({
      
          })
      })
      .then((response) => response.text()) //or response.json()
      .then((text) => {
          console.log(text);
      });
      

      另外,您需要发出一个 cors 请求,否则您无法访问响应。如果要接受来自所有来源的 ajax 请求,则需要将此全局中间件添加到 laravel

      <?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', 'GET,POST,PUT,PATCH,DELETE,OPTIONS')
                  ->header('Access-Control-Allow-Headers', 'content-type');
          }
      }
      

      阅读This article 了解全局中间件。

      【讨论】:

      • 我设置了这个确切的中间件,但我仍然收到错误消息Fetch API cannot load http://laravel.dev/content. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
      • 您必须将其添加到 app/Http/Kernel.php 中的中间件列表中
      • 我做到了。但我仍然得到一个错误,我不知道为什么。如果有帮助,我可以在 github 上创建一个 repo,因为我觉得我已经尝试了一切来让它工作。
      • 那么现在的错误是什么?我已经构建了许多由 laravel 后端驱动的 react 应用程序。我很乐意提供帮助。
      • 这是当前的错误信息Fetch API cannot load http://laravel.dev/content. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
      猜你喜欢
      • 2014-07-04
      • 2020-08-22
      • 2019-04-08
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 2020-11-14
      相关资源
      最近更新 更多