【问题标题】:Sending get request to an Laravel API using axios in Vue.js在 Vue.js 中使用 axios 向 Laravel API 发送获取请求
【发布时间】:2018-07-11 14:56:19
【问题描述】:

我使用 Laravel 5.5 创建了一个 api,并在 Postman 中对其进行了测试。因此,在 Postman 中它工作正常,但是当我尝试从前端连接它时,我遇到了一些错误。我在前端使用 Vue.js。

这是来自前端使用 axios 的请求:

<script>
  import axios from 'axios';

  export default {
    data () {
      return {
        posts: {}
      }
    }, 
    created() {
      axios({
        method: 'get',
        url: 'http://localhost:8000/api/users',
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token, Authorization',
          'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
          'Access-Control-Allow-Credentials': true,     
          'Content-Type': 'text/html; charset=utf-8'   
        }
      }).then(response => {
          this.posts = response.data;
          console.log(this.posts[0].body);          
        }).catch(error => {
          console.error(error.message);          
        });
    }
  }
</script>

还有api路由:

Route::get('users', 'UserController@index');

我收到这样的错误:

API 正在通过php artisan serve 命令在localhost:8000 上运行。 Vue.js 应用程序正在通过yarn run dev 命令在localhost:8000 上运行。 有什么解决办法吗?

【问题讨论】:

  • 标头应该来自服务器,而不是客户端。即服务器应响应客户端的请求,其中包括您编写的标头
  • 你能举个例子吗?谢谢你。

标签: laravel rest api vue.js vuejs2


【解决方案1】:

您正在从您的 axios 请求中传递 Access-Control 标头,但您还需要配置您的 Laravel 应用程序以接受来自外部来源的请求。

为此,您需要在 Laravel 应用程序中添加 CORS 标头支持。您可以使用barryvdh/laravel-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)
    {

        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

}

注册:

要使用 CORS 中间件,您必须先在 app\Http\Kernel.php 文件中注册它,如下所示:

protected $routeMiddleware = [
        //other middlewares
        'cors' => 'App\Http\Middleware\CORS',
    ];

然后在需要的路由中应用中间件:

Route::get('test', array('middleware' => 'cors', 'uses' => 'TestController@test'));

【讨论】:

  • 非常感谢。您节省了很多时间)效果很好。
  • 还有一个问题.. 像这样分离前端和后端是一种好习惯吗?因为 Vue.js 自带 Laravel 开箱即用。我的意思是分离 Laravel 和 Vue..
【解决方案2】:

您需要在服务器配置中设置 cors 标头,而不是您的请求。

Access-Control-Allow-Origin 必须设置为 *

Access-Control-Allow-Headers 必须设置为 Origin、X-Requested-With、Content-Type、Accept

这是一个 nginx 配置示例。

https://gist.github.com/tomkersten/1323477

和apache2指令

https://enable-cors.org/server_apache.html

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 2023-03-31
    • 2019-03-07
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2016-11-27
    • 2018-03-06
    • 2019-09-27
    相关资源
    最近更新 更多