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

在Laravel应用中使用remove.bg NPM包出现prototype读取错误如何解决

问题根源

你使用的remove.bg npm包是Node.js服务端环境专用包,本身没有做浏览器端兼容,依赖的unirest、zlib等都是Node.js原生模块,即便补充Webpack 5 polyfill也很容易出现兼容问题,这是本次报错的核心原因。
另外你当前的polyfill配置缺少util模块的适配,本次报错的inherits方法就来自util模块,这是直接触发报错的原因。

解决方案

方案一(最推荐,无安全风险):后端调用remove.bg接口

完全不使用前端npm包,直接在Laravel后端通过HTTP客户端调用remove.bg官方接口,既可以避免前端依赖冲突,也能防止你的remove.bg API密钥暴露在前端造成被盗刷的风险。
示例代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;

class RemoveBgController extends Controller
{
    public function process(Request $request)
    {
        // 验证前端上传的图片
        $request->validate([
            'image' => 'required|file|image'
        ]);

        $response = Http::withHeaders([
            'X-Api-Key' => env('REMOVE_BG_API_KEY')
        ])
        ->attach('image_file', $request->file('image')->get(), $request->file('image')->getClientOriginalName())
        ->post('https://api.remove.bg/v1.0/removebg');

        // 直接返回处理后的图片内容
        return response($response->body(), 200, [
            'Content-Type' => 'image/png',
            'Content-Disposition' => 'attachment; filename="no-bg.png"'
        ]);
    }
}

配置好路由后前端只需要调用你自己的后端接口即可。

方案二(临时兼容前端运行,存在安全风险):补全polyfill配置

如果一定要在前端运行该npm包,需要补充缺失的polyfill:

  1. 安装缺失的依赖包
npm install util process buffer stream-browserify --save
  1. 修改webpack.mix.js配置,补充util fallback和全局变量适配
const webpack = require('webpack');

mix.webpackConfig({
    resolve: {
        fallback: {
            util: require.resolve('util/'),
            fs: require.resolve('browserify-fs'),
            crypto: require.resolve('crypto-browserify'),
            stream: require.resolve('stream-browserify'),
            http: require.resolve('stream-http'),
            https: require.resolve('https-browserify'),
            path: require.resolve('path-browserify'),
            zlib: require.resolve('browserify-zlib'),
        },
    },
    plugins: [
        new webpack.ProvidePlugin({
            process: 'process/browser',
            Buffer: ['buffer', 'Buffer'],
        }),
    ]
});
  1. 重新运行npm run dev编译即可解决当前报错。

注意:该方案会将你的remove.bg API密钥明文暴露在前端代码中,任何人都可以抓取你的密钥调用接口产生额外费用,仅建议本地测试使用,不要上线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:24:02