React(Vite) 快速开始
- AI 快速开始
- 完整开发指引
准备工作
在开始之前,请确保您已完成以下准备:
- 创建云开发环境:创建云开发环境
- 安装 Node.js:下载 Node.js(建议 LTS 版本)
Client
配置你的 AI 工具以连接 CloudBase 能力 支持本地与托管两种连接方式,详见 连接方式。
步骤 1:安装 / 配置 CloudBase
步骤 2:和 AI 对话
在 AI 对话中依次输入以下内容:
prompt
安装 CloudBase Skills:命令 npx skills add tencentcloudbase/cloudbase-skills -y使用 CloudBase Skills: 使用 CloudBase Skills:在 React(Vite) 应用中集成 CloudBase Web SDK,包括认证和数据库功能准备工作
在开始之前,请确保您已完成以下准备:
- 创建云开发环境:创建云开发环境
- 安装 Node.js:下载 Node.js(建议 LTS 版本)
更多详情请参考:React(Vite) 完整文档
安装 SDK
@cloudbase/js-sdk 可以让您在 Web 端(如 PC Web 页面、微信公众平台 H5 等)使用 JavaScript 访问 CloudBase 服务和资源。
npm
npm i @cloudbase/js-sdk
yarn
yarn add @cloudbase/js-sdk
pnpm
pnpm add @cloudbase/js-sdk
初始化 SDK
新增如下代码到您的 React 项目
src/utils/cloudbase.js
import cloudbaseSDK from "@cloudbase/js-sdk";
export const cloudbase = cloudbaseSDK.init({
env: import.meta.env.VITE_CLOUDBASE_ENV_ID,
region: import.meta.env.VITE_CLOUDBASE_REGION,
accessKey: import.meta.env.VITE_CLOUDBASE_ACCESS_KEY,
});
.env
# 环境ID
VITE_CLOUDBASE_ENV_ID={%ENV_ID%}
# 环境所在地域
VITE_CLOUDBASE_REGION={%REGION%}
# 匿名访问令牌
VITE_CLOUDBASE_ACCESS_KEY={%PUBLISHABLE_KEY%}
身份认证
- 短信验证码注册
- 邮箱验证码注册
- 账号密码登录
- 短信验证码登录
- 邮箱验证码登录
- Google 授权登录
使用 短信验证码注册 请先前往 身份认证/登录方式 开启 短信验证码
调用方式:
import { cloudbase } from "./utils/cloudbase";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ phone_number: phone });
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code,
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
phone_number: `+86 ${phone}`,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${phone.slice(-4)}`,
password: "admin@123",
});
完整示例:
import { useState } from "react";
import { cloudbase } from "./utils/cloudbase";
function Page() {
const [phone, setPhone] = useState("");
const [code, setCode] = useState("");
const [verificationId, setVerificationId] = useState("");
const [message, setMessage] = useState("");
// 发送验证码
const sendCode = async () => {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ phone_number: phone });
setVerificationId(res.verification_id);
setMessage("验证码已发送!");
} catch (error) {
setMessage("发送失败:" + error.message);
}
};
// 注册
const register = async () => {
try {
const auth = cloudbase.auth();
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code,
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
phone_number: `+86 ${phone}`,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${phone.slice(-4)}`,
password: "admin@123",
});
setMessage("注册成功!");
} catch (error) {
setMessage("注册失败:" + error.message);
}
};
return (
<div>
<label>手机号:</label>
<input
value={phone}
onChange={(e) => setPhone(e.target.value)}
placeholder="13800000000"
/>
<div>
<label>验证码:</label>
<input
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="验证码"
/>
<button disabled={!phone} onClick={sendCode}>
发送验证码
</button>
</div>
<button disabled={!verificationId || !code} onClick={register}>
注册
</button>
{message && (
<p style={{ color: message.includes("成功") ? "green" : "red" }}>
{message}
</p>
)}
</div>
);
}
export default Page;
使用 邮箱验证码注册 请先前往 身份认证/登录方式 开启 邮箱验证码
调用方式:
import { cloudbase } from "./utils/cloudbase";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ email });
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code,
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
email,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${email.slice(-4)}`,
password: "admin@123",
});
完整示例:
import { useState } from "react";
import { cloudbase } from "./utils/cloudbase";
function Page() {
const [email, setEmail] = useState("");
const [code, setCode] = useState("");
const [verificationId, setVerificationId] = useState("");
const [message, setMessage] = useState("");
// 发送验证码
const sendCode = async () => {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ email });
setVerificationId(res.verification_id);
setMessage("验证码已发送!");
} catch (error) {
setMessage("发送失败:" + error.message);
}
};
// 注册
const register = async () => {
try {
const auth = cloudbase.auth();
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code,
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
email,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${email.slice(-4)}`,
password: "admin@123",
});
setMessage("注册成功!");
} catch (error) {
setMessage("注册失败:" + error.message);
}
};
return (
<div>
<label>邮箱:</label>
<input
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="example@email.com"
/>
<div>
<label>验证码:</label>
<input
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="验证码"
/>
<button disabled={!email} onClick={sendCode}>
发送验证码
</button>
</div>
<button disabled={!verificationId || !code} onClick={register}>
注册
</button>
{message && (
<p style={{ color: message.includes("成功") ? "green" : "red" }}>
{message}
</p>
)}
</div>
);
}
export default Page;
使用 账号密码登录 请先前往 身份认证/登录方式 开启 用户名密码登录
调用方式:
import { cloudbase } from "./utils/cloudbase";
const auth = cloudbase.auth();
await auth.signIn({
username, // 可以是用户名、手机号或邮箱
password,
});
完整示例:
import { useState } from "react";
import { cloudbase } from "./utils/cloudbase";
function Page() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [message, setMessage] = useState("");
// 登录
const login = async () => {
try {
const auth = cloudbase.auth();
await auth.signIn({
username: username, // 可以是用户名、手机号或邮箱
password: password,
});
setMessage("登录成功!");
} catch (error) {
setMessage("登录失败:" + error.message);
}
};
return (
<div>
<label>账号:</label>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="用户名/手机号/邮箱"
/>
注:手机号登录请添加区号 +86
<br />
<label>密码:</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="请输入密码"
/>
<br />
<button disabled={!username || !password} onClick={login}>
登录
</button>
{message && (
<p style={{ color: message.includes("成功") ? "green" : "red" }}>
{message}
</p>
)}
</div>
);
}
export default Page;
使用 短信验证码登录 请先前往 身份认证/登录方式 开启 短信验证码登录
调用方式:
import { cloudbase } from "./utils/cloudbase";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ phone_number: `+86 ${phone}` });
// 登录
await auth.signInWithSms({
verificationInfo: res,
verificationCode: code,
phoneNum: `+86 ${phone}`,
});
完整示例:
import { useState } from "react";
import { cloudbase } from "./utils/cloudbase";
function Page() {
const [phone, setPhone] = useState("");
const [code, setCode] = useState("");
const [verificationInfo, setVerificationInfo] = useState(null);
const [message, setMessage] = useState("");
// 发送验证码
const sendCode = async () => {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ phone_number: `+86 ${phone}` });
setVerificationInfo(res);
setMessage("验证码已发送!");
} catch (error) {
setMessage("发送失败:" + error.message);
}
};
// 登录
const login = async () => {
try {
const auth = cloudbase.auth();
await auth.signInWithSms({
verificationInfo,
verificationCode: code,
phoneNum: `+86 ${phone}`,
});
setMessage("登录成功!");
} catch (error) {
setMessage("登录失败:" + error.message);
}
};
return (
<div>
<label>手机号:</label>
<input
value={phone}
onChange={(e) => setPhone(e.target.value)}
placeholder="13800000000"
/>
<div>
<label>验证码:</label>
<input
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="验证码"
/>
<button onClick={sendCode} disabled={!phone}>
发送验证码
</button>
</div>
<button onClick={login} disabled={!verificationInfo || !code}>
登录
</button>
{message && (
<p style={{ color: message.includes("成功") ? "green" : "red" }}>
{message}
</p>
)}
</div>
);
}
export default Page;
使用 邮箱验证码登录 请先前往 身份认证/登录方式 开启 邮箱验证码
调用方式:
import { cloudbase } from "./utils/cloudbase";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ email });
// 登录
await auth.signInWithEmail({
verificationInfo: res,
verificationCode: code,
email,
});
完整示例:
import { useState } from "react";
import { cloudbase } from "./utils/cloudbase";
function Page() {
const [email, setEmail] = useState("");
const [code, setCode] = useState("");
const [verificationInfo, setVerificationInfo] = useState(null);
const [message, setMessage] = useState("");
// 发送验证码
const sendCode = async () => {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ email });
setVerificationInfo(res);
setMessage("验证码已发送!");
} catch (error) {
setMessage("发送失败:" + error.message);
}
};
// 登录
const login = async () => {
try {
const auth = cloudbase.auth();
await auth.signInWithEmail({
verificationInfo,
verificationCode: code,
email,
});
setMessage("登录成功!");
} catch (error) {
setMessage("登录失败:" + error.message);
}
};
return (
<div>
<label>邮箱:</label>
<input
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="example@email.com"
/>
<div>
<label>验证码:</label>
<input
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="验证码"
/>
<button onClick={sendCode} disabled={!email}>
发送验证码
</button>
</div>
<button onClick={login} disabled={!verificationInfo || !code}>
登录
</button>
{message && (
<p style={{ color: message.includes("成功") ? "green" : "red" }}>
{message}
</p>
)}
</div>
);
}
export default Page;
使用 Google 授权登录 请先前往 身份认证/登录方式 开启 Google 授权登录
调用方式:
import { cloudbase } from "./utils/cloudbase";
const auth = cloudbase.auth();
// 步骤1:生成Google授权URL并跳转
const state = Date.now().toString();
localStorage.setItem("google_login_state", state);
const { uri } = await auth.genProviderRedirectUri({
provider_id: "google",
provider_redirect_uri: window.location.href,
state: state,
});
window.location.href = uri;
// 步骤2:使用code换取provider_token
const { provider_token } = await auth.grantProviderToken({
provider_id: "google",
provider_redirect_uri: window.location.origin + window.location.pathname,
provider_code: code,
});
// 步骤3:使用provider_token登录
await auth.signInWithProvider({
provider_token: provider_token,
});
完整示例:
import { useState, useEffect } from "react";
import { cloudbase } from "./utils/cloudbase";
function Page() {
const [message, setMessage] = useState("");
const [isCallback, setIsCallback] = useState(false);
useEffect(() => {
// 检查是否是Google回调页面
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get("code");
const state = urlParams.get("state");
if (code && state) {
setIsCallback(true);
handleGoogleCallback(code, state);
}
}, []);
// 步骤1:跳转到Google授权页
const startGoogleLogin = async () => {
try {
const auth = cloudbase.auth();
const state = Date.now().toString(); // 生成唯一标识,防止CSRF攻击
// 保存state到本地,用于回调时验证
localStorage.setItem("google_login_state", state);
// 生成Google授权URL
const { uri } = await auth.genProviderRedirectUri({
provider_id: "google", // 固定值,代表Google开放平台
provider_redirect_uri: window.location.href, // 授权后回调当前页面
state: state,
});
// 跳转到Google授权页
window.location.href = uri;
} catch (error) {
setMessage("跳转失败:" + error.message);
}
};
// 步骤2和3:处理Google回调并完成登录
const handleGoogleCallback = async (code, state) => {
try {
// 验证state是否匹配,防止CSRF攻击
const savedState = localStorage.getItem("google_login_state");
if (savedState !== state) {
setMessage("登录失败:状态验证失败");
return;
}
const auth = cloudbase.auth();
// 使用code换取provider_token
const { provider_token } = await auth.grantProviderToken({
provider_id: "google",
provider_redirect_uri:
window.location.origin + window.location.pathname,
provider_code: code,
});
try {
// 尝试直接登录
await auth.signInWithProvider({
provider_token: provider_token,
});
setMessage("登录成功!");
// 清除URL参数并清除本地存储
localStorage.removeItem("google_login_state");
window.history.replaceState(
{},
document.title,
window.location.pathname
);
} catch (loginError) {
// 如果是首次Google登录,需要先注册并绑定
if (loginError.error === "not_found") {
setMessage("检测到首次Google登录,需要绑定账号...");
// 这里需要引导用户完成注册流程
// 例如:收集手机号验证码进行注册
// 注册成功后调用 bindWithProvider 绑定Google身份
// 示例:假设已有其他方式注册的账号,直接绑定
await auth.bindWithProvider({
provider_token: provider_token,
});
// 绑定成功后重新登录
await auth.signInWithProvider({
provider_token: provider_token,
});
setMessage("绑定并登录成功!");
// 清除URL参数和本地存储
localStorage.removeItem("google_login_state");
window.history.replaceState(
{},
document.title,
window.location.pathname
);
} else {
throw loginError;
}
}
} catch (error) {
setMessage("登录失败:" + error.message);
localStorage.removeItem("google_login_state");
}
};
return (
<div>
{!isCallback && <button onClick={startGoogleLogin}>Google登录</button>}
{isCallback && <p>正在处理Google登录...</p>}
{message && (
<p style={{ color: message.includes("成功") ? "green" : "red" }}>
{message}
</p>
)}
</div>
);
}
export default Page;