ThinkPHP 5 1 跨域配置方法

2022-10-04 08:48:06 字數 1843 閱讀 3647

因為最近的專案採用了api介面開發方式,後端需要配置跨域的規則以便前端能夠訪問。

系統採用的框架為 thinkphp,版本 5.1.19

關於options請求

由於前端的知識不是很熟悉,查閱了網上的資料得知,options 請求是在 ajax 傳送請求前傳送的乙個驗證請求,該請求會驗證一系列規則,若符合規則則會傳送實際的 get 或 post 請求,跨域的規則也是 options 請求時進行驗證的。

遇到的問題

按照網上大部分關於跨域請求的配置,基本都是以下三行**:

header("access-control-allow-origin: *");

header("access-control-allow-headers: origin, x-re程式設計客棧quested-with, content-type, accept, authorization");

header('access-control-allow-methods: get,post,put,delete,options,patch');

把這三行**放到 /route/route.php,/route/api.php,/public/index.php 以及受訪問的控制器檔案頭部均出現以下報錯資訊:

說明配置並沒有生效。

查閱 thinkphp 的文件,文件給出的例子:

route::get('new/:id', 'news/read')

->ext('html')

->allowcrossdomain();

意思是只需要在路由的尾部新增 allowcrossdomain() 即可,所以我在每個需要進行跨域訪問的路由後都新增了 ->allowcrossdomain(),問題得以解決。

另外的問題

由於前端的 ajax 請求通常需要攜帶 token 驗證,所以還需要將 token 新增到 access-control-allow-headers

文件的例子是

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') ,再次請求出現了下面的報錯:

failed to load: 程式設計客棧m/main/info: request header field token is not allowed by access-control-allow-headers in preflight response.

header 的配置沒有生效。

解決辦法:將 header('access-control-allow-headers: content-type,token'); 新增到 入口檔案 /public/index.php 即可。

本文標題: thinkphp 5.1 跨域配置方法

本文位址: /wangluo/php/280580.html

ThinkPHP5 1鉤子和行為

tp5.1的行為是乙個比較抽象的概念,執行的流程使用者的註冊,登入,退出登入等等都可以作為乙個行為。而不同的行為之間也具有位置共同性,比如,有些行為的作用位置在使用者註冊後,在登入之後,退出登入之後,等等有些行為的作用位置都是在應用執行前,有些行為都是在模板輸出之後,把這些行為發生作用的位置稱之為鉤...

thinkphp5 1 匯入excel檔案

public function importexcel 限制上傳 型別 ext substr strrchr files file name 1 if ext xls ext xlsx 讀取 filename files file tmp name reader iofactory createre...

ThinkPHP5 1學習 模組設計

一 目錄結構 thinkphp5.1 預設是多模組架構,也可以設定為單模組操作 手冊摘入的結構列表 多模組設計在 url 訪問時,必須指定響應的模組名,比如 public test abc eat 如果你只有 test 這乙個模組時,你可以繫結這個模組,從而省略寫法 此時,url 呼叫就變成了 pu...