You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt.js中使用Axios调用PHP API出现Network Error问题求助

Fixing "Network Error" When Fetching Data from PHP API in Nuxt.js with Axios

Hey Ali, let's walk through the most likely causes of that Network Error and how to fix them step by step:

1. CORS (Cross-Origin Resource Sharing) Block

This is the #1 reason for cross-origin request failures. If your Nuxt app is running on a different origin (like http://localhost:3000 while your API lives on https://joozveh.ir), browsers will block the request unless your PHP server explicitly allows it.

Add these CORS headers at the very top of your test.php file:

// Allow cross-origin requests (adjust origin for production!)
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
// Ensure the response is marked as JSON
header("Content-Type: application/json");

$data = array("id"=>1,"name"=>"ali");
echo json_encode($data);

Pro tip: For production, replace * with your actual Nuxt app domain (e.g., https://your-nuxt-site.com) to lock down security.

2. Verify Your API is Actually Reachable

First, test the API directly: open https://joozveh.ir/api/test.php in your browser. You should see plain JSON output: {"id":1,"name":"ali"}.

  • If you get a 404, double-check the file path (maybe it's in a different folder, or there's a typo in your URL).
  • If you get a server error (500), check your PHP error logs for syntax issues.

3. Tweak Nuxt Axios Configuration

If you're using Nuxt's official @nuxtjs/axios module, make sure your nuxt.config.js is set up properly:

// nuxt.config.js
export default {
  modules: ['@nuxtjs/axios'],
  axios: {
    baseURL: 'https://joozveh.ir/api', // Shortens your request paths
    browserBaseURL: 'https://joozveh.ir/api'
  }
}

Then you can simplify your request to:

axios.get('/test.php')
  .then(res => console.log(res.data))
  .catch(e => console.error('Request failed:', e))

4. Check for Mixed Content Issues

If your local Nuxt app runs on http://localhost but your API uses https://, some browsers block "mixed content". For testing, you can either:

  • Run your local Nuxt app over HTTPS (use tools like mkcert to generate local SSL certs)
  • Temporarily disable mixed content blocking in your browser settings (only for development!)

5. Dig Into the Real Error Details

Don't stop at the generic "Network Error" message. Open your browser's DevTools > Network tab, find the failed request, and check:

  • The Status Code (e.g., 403, 500, or 0 for blocked requests)
  • The Response tab for server-side error messages
  • The Console tab for more specific browser logs

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 07:37:41