本篇文章给大家带来的内容是关于Laravel API跨域访问的实现步骤,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

服务器A请求服务器B的接口,那么一般会出现跨域问题。

1

XMLHttpRequest cannot load http://api.console.vms3.com/api/user. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' istherefore not allowed access.

意思就是服务器响应不允许跨域访问.

那我们就需要让服务器支持跨域访问, 也就是在响应头部中添加

1

'Access-Control-Allow-Origin: *'

第一步: 创建中间件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

创建 `app/Http/Middleware/AccessControlAllowOrigin.php` middleware 把 'Access-Control-Allow-Origin: *' 写入头部.

app/Http/Middleware/AccessControlAllowOrigin.php

<?php

namespace App\Http\Middleware;

use Closure;

use Illuminate\Support\Facades\Auth;

class AccessControlAllowOrigin

{

    /**

     *

     * 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: *');

        header("Access-Control-Allow-Credentials: true");

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

        header("Access-Control-Allow-Headers: Content-Type,Access-Token");

        header("Access-Control-Expose-Headers: *");

        return $next($request);

    }

}

第二步: 注册路由

注册这个 middleware 到 kernel 中. 
分别在 protected $middleware 数组中和 protected $routeMiddleware 数组中
添加我们刚才创建的那个文件class名, 使用 cors 这个别名.

链接:https://pan.baidu.com/s/1v5gm7n0L7TGyejCmQrMh2g 提取码:x2p5

免费分享,但是X度限制严重,如若链接失效点击链接或搜索加群 群号518475424

第三步: 设置中间件保护接口

然后在设置它保护 api , 就是$middlewareGroups['api'] 的数组中添加它的别名, 本文中是 'cors'
app/Http/Kernel.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel

{

    /**

     * The application's global HTTP middleware stack.

     *

     * These middleware are run during every request to your application.

     *

     * @var array

     */

    protected $middleware = [

        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,

        \App\Http\Middleware\TrimStrings::class,

        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

        \App\Http\Middleware\AccessControlAllowOrigin::class,

    ];

    /**

     * The application's route middleware groups.

     *

     * @var array

     */

    protected $middlewareGroups = [

        'web' => [

            \App\Http\Middleware\EncryptCookies::class,

            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,

            \Illuminate\Session\Middleware\StartSession::class,

            // \Illuminate\Session\Middleware\AuthenticateSession::class,

            \Illuminate\View\Middleware\ShareErrorsFromSession::class,

            \App\Http\Middleware\VerifyCsrfToken::class,

            \Illuminate\Routing\Middleware\SubstituteBindings::class,

        ],

        'api' => [

            'throttle:60,1',

            'bindings',

            'cors'

        ],

    ];

    /**

     * The application's route middleware.

     *

     * These middleware may be assigned to groups or used inpidually.

     *

     * @var array

     */

    protected $routeMiddleware = [

        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,

        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,

        'can' => \Illuminate\Auth\Middleware\Authorize::class,

        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        'cors' => \App\Http\Middleware\AccessControlAllowOrigin::class,

    ];

}

第四步:在路由中添加路由

1

2

3

Route::middleware('cors')->group(function () {

    //

});

以上就是Laravel API跨域访问的实现步骤的详细内容。

Laravel API跨域访问的实现步骤的更多相关文章

  1. Web Api跨域访问配置及调用示例

    1.Web Api跨域访问配置. 在Web.config中的system.webServer内添加以下代码: <httpProtocol> <customHeaders> &l ...

  2. Web API 跨域访问(CORS)

    1.在web.config里把“    <remove name="OPTIONSVerbHandler" />  ”删掉. 2. 到nuget上装一个包:    ht ...

  3. ASP.NET Web API 跨域访问(CORS)

    一.客户端用JSONP请求数据 如果你想用JSONP来获得跨域的数据,WebAPI本身是不支持javascript的callback的,它返回的JSON是这样的: {"YourSignatu ...

  4. ASP.NET Web API 跨域访问(CORS)要注意的地方

    一.客户端用JSONP请求数据 如果你想用JSONP来获得跨域的数据,WebAPI本身是不支持javascript的callback的,它返回的JSON是这样的: {"YourSignatu ...

  5. asp.net关于如何准许api跨域访问

    首先需要在原api接口的程序中在web.config添加如下节点(在<system.webServer>节点下) <!--准许跨域请求--> <httpProtocol& ...

  6. ASP.NET Web API 跨域访问

    自定义特性 要在WebApi中实现JSONP,一种方式是实现自定义特性  http://stackoverflow.com/questions/9421312/jsonp-with-asp-net-w ...

  7. web api 跨域访问

    在工程中 Install-Package Microsoft.AspNet.WebApi.Cors 在 webapiconfig.cs中 config.EnableCors(); 在 控制器中, [E ...

  8. 设置IE浏览器跨域访问数据

    在开发中,经常会遇到多站点跨域访问后台服务获取数据的情况,解决方法有两种 自己写代理服务,访问代理服务,代理服务请求服务获取数据再返回: 设置浏览器可以跨域访问数据. 本文来讲如何设置IE浏览器跨域访 ...

  9. Laravel API 允许跨域访问

    服务器A请求服务器B的接口,那么一般会出现跨域问题.全解跨域请求处理办法 XMLHttpRequest cannot load http://api.console.vms3.com/api/user ...

随机推荐

  1. python SSL 错误

    python 使用pip 安装模块是提示SSL错误 出现该问题的原因由于系统的openssl是1.0.1的版本,对于python3.7太老了,需要更新为openssl1.0.2或者libressl2. ...

  2. leetcode209. 长度最小的子数组

    双指针滑动窗口解法,时间复杂度O(N). 滑动窗口,想象一下,在一个坐标上存在两个指针begin 和i ,begin 代表滑窗的左边框,i代表滑窗的右边框.两者通过分别向右滑动,前者能使窗口之间的和减 ...

  3. flutter:Could not download kotlin-gradle-plugin.jar

    我们可以看到是flutter的外部依赖:kotlin-gradle-plugin-1.2.71 下载不了,下面我介绍使用手动下载的方式去解决: 首先,看到flutter项目目录,注意我标出的是运行项目 ...

  4. 动态规划 | 保留重复元素的LCS 1045

    这题也可以用LIS求解.LIS解题报告:动态规划 | 对输入进行hash处理的LIS 1045 普通LCS是必须完全匹配的,所以状态转移方程式(末端匹配到时):dp[i][j]=dp[i-1][j-1 ...

  5. 洛谷p3384【模板】树链剖分题解

    洛谷p3384 [模板]树链剖分错误记录 首先感谢\(lfd\)在课上调了出来\(Orz\) \(1\).以后少写全局变量 \(2\).线段树递归的时候最好把左右区间一起传 \(3\).写\(dfs\ ...

  6. [LeetCode] 1123. Lowest Common Ancestor of Deepest Leaves 最深叶结点的最小公共父节点

    Given a rooted binary tree, return the lowest common ancestor of its deepest leaves. Recall that: Th ...

  7. [LeetCode] 719. Find K-th Smallest Pair Distance 找第K小的数对儿距离

    Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pai ...

  8. Chrome操作技巧

    好用的插件: 如果你用 Chrome 浏览器,这8款插件一定要用! - 知乎 沙拉查词:     集合各大翻译,详细好用权威 Simple Allow Copy: 开启被网页屏蔽的自由复制功能 Qui ...

  9. 整理在Spring IOC容器初始化后可以处理特定逻辑的多种实现方式

    Spring框架的核心是依赖注入.切面:Spring Boot是在Spring框架的基础上为其提供许多默认配置.默认约定(约定优于配置),从而达到减少或减化配置进而可开箱即用.快速上手:Spring ...

  10. 第29课 互斥量与自解锁(std::mutex和lock系列)

    一. 互斥量 (一)Mutex系列类 1. std::mutex:独占的互斥量,不能递归使用. 2. std::recursive_mutex:递归互斥量.允许同一线程多次获得该互斥锁,可以用来解决同 ...