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

React中使用bcrypt报错无法解析'tls'的原因及解决方法

Hey there! Let's break down why you're hitting this error and fix it properly.

What's Causing the Error?

The core issue here is that bcrypt is a Node.js-exclusive library — it relies on core Node.js modules like tls, net, and fs that don't exist in browser environments. If you're trying to run this code in a frontend project (like Vue/React) or a build setup that doesn't support Node's core modules (e.g., Webpack bundling for the browser), your bundler will fail to resolve those missing modules, throwing the "Can't resolve 'tls'" error you're seeing.

Also, a critical note: password hashing in the frontend is a bad security practice. Any encryption logic or keys you use client-side are exposed to attackers, making the "encrypted" password no more secure than sending plaintext (especially if you're not using HTTPS, which you absolutely should be).

How to Fix It

Let's start with the correct, secure approach, then cover alternatives if you have a specific use case:

This is the only secure way to handle password hashing:

  • Keep your frontend code simple: send the plaintext password to your Node.js backend API over HTTPS.
  • In your backend (e.g., Express/Koa server), use bcrypt to hash the password before storing it in your database.
    Example backend code snippet:
    const bcrypt = require('bcrypt');
    // When handling a registration/login request
    const hashedPassword = bcrypt.hashSync(req.body.password, 10);
    // Store hashedPassword in your DB instead of the plaintext
    

2. Use a Browser-Friendly Alternative (If You Must Hash Client-Side)

If you have a specific reason to hash in the frontend (though I still don't recommend it), use bcryptjs — a pure JavaScript implementation of bcrypt that doesn't depend on Node core modules:

  • Install it:
    npm install bcryptjs --save
    
  • Replace your existing code with:
    var bcrypt = require('bcryptjs');
    var hash = bcrypt.hashSync(values.newPassword, 10);
    

3. Adjust Webpack Config (Last Resort)

If you're stuck using the original bcrypt in a non-Node environment, you can tell Webpack to ignore the missing core modules. This can lead to other unexpected issues, so only do this if you know what you're doing:
Add this to your webpack.config.js:

module.exports = {
  // ... your existing config
  resolve: {
    fallback: {
      "tls": false,
      "net": false,
      "fs": false,
      // Add other missing modules here if you get similar errors
    }
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:42:42