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

Next.js 12.2.2启动时遇TypeError: terminated错误求助

问题:Next.js 12.2.2调用Laravel 10 API时出现TypeError: terminated错误

启动Next.js 12.2.2项目时触发TypeError: terminated错误,项目从Laravel 10根路径调用两个API,同款项目在他人电脑上运行正常,无法定位错误原因。

API调用代码

调用website-setup API的代码(NEXT_PUBLIC_BASE_URL = http://127.0.0.1:8000):

axios
      .get(`${process.env.NEXT_PUBLIC_BASE_URL}api/website-setup`)
      .then((res) => {
        // handle success
        dispatch(setupAction(res.data));
        localStorage.setItem(
          "settings",
          JSON.stringify(res.data && res.data.setting)
        );
        localStorage.setItem("pusher", JSON.stringify(res.data && res.data.pusher_info ? res.data.pusher_info :null));
        if (res.data) {
          setFbPixel(res.data.facebookPixel);
          localStorage.setItem("language", JSON.stringify(res.data.language));
          const checkLangExists = localStorage.getItem("language");
          if (checkLangExists) {
            setLoad(false);
            if(!messageWid){
              if(localStorage.getItem("pusher")){
                const pusher = JSON.parse(localStorage.getItem("pusher"));
                setMessageWid(pusher);
              }
            }
          }
        }
      })
      .catch((error) => {
        // handle error
        console.log(error);
      });

后端返回数据

{
 "setting": {
        "logo": null,
        "favicon": null,
        "enable_user_register": 1,
        "phone_number_required": 1,
        "default_phone_code": "IN",
        "enable_multivendor": 1,
        "text_direction": "LTR",
        "timezone": "Asia/Calcutta",
        "topbar_phone": null,
        "topbar_email": "info@example.com",
        "currency_icon": "₹",
        "currency_name": "INR",
        "show_product_progressbar": 1,
        "theme_one": "#fffb00",
        "theme_two": "#b1a306",
        "seller_condition": null
    },
    "maintainance": {
        "id": 1,
        "status": 0,
        "image": "",
        "description": "",
        "created_at": "2023-07-24T12:58:38.000000Z",
        "updated_at": "2023-07-24T12:58:38.000000Z"
    },
    "flashSaleActive": true,
    "flashSale": {
        "status": 1,
        "offer": 10,
        "end_time": "2023-07-24"
    },
    "flashSaleProducts": [],
    "announcementModal": {
        "id": 1,
        "status": 1,
        "title": "GET UP TO 75% OFF",
        "description": "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Exercitationem, facere nesciunt doloremque nobis debitis sint?",
        "image": "uploads/website-images/announcement-2022-11-19-12-33-21-4518.png",
        "expired_date": 5,
        "created_at": "2023-07-24T12:58:39.000000Z",
        "updated_at": "2023-07-24T12:58:39.000000Z"
    },
    "productCategories": [],
    "megaMenuCategories": [],
    "megaMenuBanner": {
        "id": 10,
        "header": null,
        "title": null,
        "link": "https://shopo-ecom.vercel.app/products?category=game",
        "image": "storage/uploads/website-images/Mega-menu-2022-10-27-01-44-55-7811.png",
        "banner_location": "Megamenu banner",
        "after_product_qty": 0,
        "status": 1,
        "created_at": null,
        "updated_at": null,
        "title_one": "SMART WATCH",
        "title_two": "Samsung Smart Watch",
        "badge": "",
        "product_slug": "electronics"
    },
    "customPages": [],
    "googleAnalytic": {
        "id": 1,
        "analytic_id": "5248-fd-5fds",
        "status": 1,
        "created_at": "2023-07-24T12:58:39.000000Z",
        "updated_at": "2023-07-24T12:58:39.000000Z"
    },
    "facebookPixel": {
        "id": 1,
        "status": 1,
        "app_id": "fsdf45sdf4sdf",
        "created_at": "2023-07-24T12:58:39.000000Z",
        "updated_at": "2023-07-24T12:58:39.000000Z"
    },
    "tawk_setting": null,
    "cookie_consent": {
        "id": 1,
        "status": 1,
        "border": "thin",
        "corners": "normal",
        "background_color": "#184dec",
        "text_color": "#fafafa",
        "border_color": "#0a58d6",
        "btn_bg_color": "#fffceb",
        "btn_text_color": "#222758",
        "message": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the when an unknown printer took.",
        "link_text": "More Info",
        "btn_text": "Yes",
        "link": null,
        "created_at": "2023-07-24T12:58:39.000000Z",
        "updated_at": "2023-07-24T12:58:39.000000Z"
    },
    "seo_setting": [
        {
            "id": 1,
            "page_name": "Home Page",
            "seo_title": "Home - Welcome to ShopO",
            "seo_description": "A best ecommerce script",
            "created_at": null,
            "updated_at": null
        },
        {
            "id": 2,
            "page_name": "About Us",
            "seo_title": "About Us - Ecommerce",
            "seo_description": "About Us",
            "created_at": null,
            "updated_at": null
        },
        {
            "id": 3,
            "page_name": "Contact Us",
            "seo_title": "Contact Us - Ecommerce",
            "seo_description": "Contact Us",
            "created_at": null,
            "updated_at": null
        },
        {
            "id": 4,
            "page_name": "Seller Page",
            "seo_title": "Our Seller - Ecommerce",
            "seo_description": "Seller Page",
            "created_at": null,
            "updated_at": null
        },
        {
            "id": 5,
            "page_name": "Blog",
            "seo_title": "Blog - Ecommerce",
            "seo_description": "Blog",
            "created_at": null,
            "updated_at": null
        },
        {
            "id": 6,
            "page_name": "Flash Deal",
            "seo_title": "Flash Deal - Ecommerce",
            "seo_description": "Flash Deal",
            "created_at": null,
            "updated_at": null
        },
        {
            "id": 7,
            "page_name": "Shop Deal",
            "seo_title": "Shop Deal - Ecommerce",
            "seo_description": "Shop Deal",
            "created_at": null,
            "updated_at": null
        }
    ],
    "filter_price_range": 5000,
    "footer_first_col": {
        "col_links": [],
        "columnTitle": "Feature"
    },
    "footer_second_col": {
        "col_links": [],
        "columnTitle": "General Links"
    },
    "footer_third_col": {
        "col_links": [],
        "columnTitle": "Helpful"
    },
    "footer": {
        "id": 1,
        "about_us": "We know there are a lot of threa developers our but we pride into a firm in the industry.",
        "phone": "+91 01682 825 123",
        "email": "digitalmelodic@gmail.com",
        "address": "Gazipara lane, Dhaltitha, 743412",
        "first_column": "Feature",
        "second_column": "General Links",
        "third_column": "Helpful",
        "copyright": "©2023 Digital Melodic - All rights reserved",
        "payment_image": "uploads/website-images/payment-card-2022-09-26-12-59-29-8933.png",
        "created_at": "2023-07-24T12:58:39.000000Z",
        "updated_at": "2023-07-24T12:58:39.000000Z"
    },
    "social_links": [],
    "image_content": {
        "empty_cart": null,
        "empty_wishlist": null,
        "change_password_image": null,
        "become_seller_avatar": null,
        "become_seller_banner": null,
        "login_image": null,
        "error_page": null
    }
}

终端错误信息

error - TypeError: terminated
    at Fetch.onAborted (node:internal/deps/undici/undici:7091:53)
    at Fetch.emit (node:events:513:28)
    at Fetch.terminate (node:internal/deps/undici/undici:6352:14)
    at Object.onError (node:internal/deps/undici/undici:7185:36)
    at Request.onError (node:internal/deps/undici/undici:2643:31)
    at errorRequest (node:internal/deps/undici/undici:4585:17)
    at Socket.onSocketClose (node:internal/deps/undici/undici:4040:9)
    at Socket.emit (node:events:513:28)
    at TCP.<anonymous> (node:net:313:12) {
  page: '/',
  [cause]: SocketError: closed
      at Socket.onSocketClose (node:internal/deps/undici/undici:4028:35)
      at Socket.emit (node:events:513:28)
      at TCP.<anonymous> (node:net:313:12) {
    code: 'UND_ERR_SOCKET',
    socket: {
      localAddress: undefined,
      localPort: undefined,
      remoteAddress: undefined,
      remotePort: undefined,
      remoteFamily: undefined,
      timeout: undefined,
      bytesWritten: 175,
      bytesRead: 4006
    }
  }

解决方案

这个错误本质是Socket连接提前关闭,结合环境差异,按以下步骤排查:

1. 检查Laravel服务状态

  • 确认Laravel的artisan serve是否正常运行,端口是否为8000
  • 直接在浏览器访问http://127.0.0.1:8000/api/website-setup,验证是否能正常返回JSON数据
  • 若浏览器访问失败,排查Laravel路由配置、CORS设置,确保API路径正确

2. 修复API路径拼写错误

代码中URL拼接可能缺少斜杠,若NEXT_PUBLIC_BASE_URL末尾无斜杠,最终URL会变成http://127.0.0.1:8000api/website-setup,触发404后导致连接终止。修改代码:

axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/api/website-setup`)

强制添加斜杠,避免路径拼接错误。

3. 调整Next.js的undici配置(针对Next.js 12.x)

Next.js 12使用undici作为HTTP客户端,部分Node.js版本存在兼容性问题。在next.config.js中添加配置:

module.exports = {
  async headers() {
    return [
      {
        source: '/api/:path*',
        headers: [
          { key: 'Access-Control-Allow-Credentials', value: 'true' },
          { key: 'Access-Control-Allow-Origin', value: '*' },
          { key: 'Access-Control-Allow-Methods', value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT' },
          { key: 'Access-Control-Allow-Headers', value: 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version' },
        ],
      },
    ];
  },
  // 禁用undici的HTTP/2,回退到HTTP/1.1
  experimental: {
    http2: false,
  },
};

4. 检查Node.js版本差异

Next.js 12.2.2推荐使用Node.js 16.x或18.x,避免过旧或过新版本。运行node -v查看版本,不一致则切换到兼容版本。

5. 清除缓存并重启服务

  • 删除Next.js的.next文件夹和node_modules/.cache目录,清除项目缓存
  • 运行php artisan cache:clear && php artisan config:clear清除Laravel缓存
  • 重新安装依赖后,重启Next.js和Laravel服务

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 05:29:49