Directus Javascript SDK 6.1.1版本连接方法咨询(文档示例不兼容)
Hey there! No worries about the confusion—this is a common issue since the SDK changed its initialization pattern between v5.3.4 and v6.1.1. The old new DirectusSDK(...) syntax from the v5 docs won't work for the newer version, but switching to the updated pattern is straightforward.
Step 1: Correct Initialization Syntax
When using the UMD build (the script you referenced), the global DirectusSDK object now contains a Directus class that you'll use to create your client instance. Here's the proper way to initialize it:
// Replace with your Directus instance URL const directusUrl = 'https://your-directus-instance.com'; // Initialize the client const client = new DirectusSDK.Directus(directusUrl, { // Optional: Add auth configuration if needed auth: { // Option 1: Use a static token staticToken: 'your-static-token-here', // Option 2: Use email/password (for dynamic login) // email: 'your-email@example.com', // password: 'your-password' } });
Step 2: Authenticate (If Required)
If you're using email/password instead of a static token, you'll need to log in explicitly with an async function:
async function connectToDirectus() { try { // Log in with credentials await client.auth.login({ email: 'your-email@example.com', password: 'your-password' }); console.log('Successfully connected to Directus!'); // Test the connection by fetching project info const projectDetails = await client.project.read(); console.log('Project Info:', projectDetails); } catch (error) { console.error('Connection failed:', error.message); } } // Run the connection function connectToDirectus();
For ES Module Users (Webpack/Rollup/Vite)
If you're using a module bundler instead of the UMD script, the import syntax is also updated:
import { Directus } from '@directus/sdk-js'; const client = new Directus('https://your-directus-instance.com', { auth: { /* Your auth config */ } });
Key Changes from v5.3.4
- The main constructor was renamed from
DirectusSDKtoDirectus(nested under the globalDirectusSDKobject in UMD builds) - The parameter structure was revised: the first argument is now your Directus instance URL, followed by a configuration object (instead of separate arguments for URL, token, etc.)
- Authentication is handled via the
authproperty in the config, with clear options for static tokens or dynamic login
内容的提问来源于stack exchange,提问作者anoren

