ThinkPHP 5.1.37 开发跨域问题解决

1.查阅 ThinkPHP 的文档,文档给出的例子:php

Route::get('new/:id', 'News/read')
    ->ext('html')
    ->allowCrossDomain();

只须要在路由的尾部添加 allowCrossDomain() 便可实现跨域请求,因此我在每一个须要进行跨域访问的路由后都添加了 ->allowCrossDomain(),通常的跨域问题得以解决。可是有的路由仍是跨域失败?html

另外的问题

2.通过百度搜索,找到缘由是因为前端的 AJAX 请求一般须要携带 token 验证,因此还须要将 token 添加到 Access-Control-Allow-Headers前端

文档的例子是:thinkphp

Route::get('new/:id', 'News/read')
    ->ext('html')
    ->header('Access-Control-Allow-Origin','thinkphp.cn')
    ->header('Access-Control-Allow-Credentials', 'true')
    ->allowCrossDomain();

按照上面的方法添加 ->header('Access-Control-Allow-Headers','token') ->allowCrossDomain();代码以下:跨域

Route::get('your route', 'News/read')
    ->header('Access-Control-Allow-Headers', 'token')
    ->allowCrossDomain();

ok,跨域问题解决;thinkphp5

相关文章
相关标签/搜索