Configuring ThinkPHP to Return JSON and Enable CORS for Vue Integration
This guide explains how to configure ThinkPHP to return JSON by default, set up individual JSON responses, and resolve Vue's cross‑origin request issues by adding appropriate Access‑Control‑Allow‑Origin headers in controller actions, with code examples for each step.
ThinkPHP by default returns HTML; to make it return JSON globally, modify the config file config.php and set the entry 'default_return_type' => 'json'.
Alternatively, you can return JSON for a specific action by using return json(['name' => 'thinkphp', 'status' => '1'], 200);, which outputs {"name":"thinkphp","status":"1"}.
When Vue communicates with the backend via axios, cross‑origin requests are blocked unless the server sends the appropriate CORS header. Add the header header('Access-Control-Allow-Origin: *'); at the beginning of the controller action.
After adding the header, the Vue axios request can reach the ThinkPHP endpoint without CORS errors.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
