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.

php Courses
php Courses
php Courses
Configuring ThinkPHP to Return JSON and Enable CORS for Vue Integration

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendVuePHPCORSThinkPHP
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.