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

使用surrealdb.js出现fetch failed错误,该如何解决?

使用surrealdb.js连接SurrealDB时遇到连接错误

我在尝试用surrealdb.js搭建SurrealDB时遇到了连接错误,错误截图显示连接相关异常。以下是我的代码:

import { Surreal } from 'surrealdb.js';

const db = new Surreal();

async function main() {
    try {
        // Connect to the database
        await db.connect('http://127.0.0.1:8000/rpc', {
            // Set the namespace and database for the connection
            namespace: 'test',
            database: 'test',

            // Set the authentication details for the connection
            auth: {
                namespace: 'test',
                database: 'test',
                scope: 'user',
                username: 'root',
                password: 'root',
            },
        });

        // Create a new person with a random id
        const created = await db.create('person', {
            title: 'Founder & CEO',
            name: {
                first: 'Tobie',
                last: 'Morgan Hitchcock',
            },
            marketing: true,
            identifier: Math.random().toString(36).substr(2, 10),
        });

        // Update a person record with a specific id
        const updated = await db.merge('person:jaime', {
            marketing: true,
        });

        // Select all people records
        const people = await db.select('person');

        // Perform a custom advanced query
        const groups = await db.query(
            'SELECT marketing, count() FROM type::table($tb) GROUP BY marketing',
            {
                tb: 'person',
            }
        );
    } catch (e) {
        console.error('ERROR', e);
    }
}

main();

我已经尝试替换连接端点的开头部分(比如切换http/ws),但问题依旧,找不到解决途径,希望得到帮助。


解决建议

1. 验证SurrealDB服务运行状态

先确认本地SurrealDB服务已启动并监听127.0.0.1:8000端口:

  • 执行surreal status查看服务状态
  • 直接访问http://127.0.0.1:8000,若返回SurrealDB的默认页面则服务正常

2. 修正连接配置的auth参数格式

根据surrealdb.js官方文档,auth字段无需重复传入namespace和database,这两个参数应放在连接配置顶层。修改后的连接代码:

await db.connect('http://127.0.0.1:8000/rpc', {
    namespace: 'test',
    database: 'test',
    auth: {
        scope: 'user',
        username: 'root',
        password: 'root',
    },
});

3. 确认命名空间与数据库已创建

确保test命名空间和数据库已提前创建,可通过SurrealDB CLI执行:

# 进入SQL交互模式
surreal sql -u root -p root --ns test --db test
# 执行创建命令
CREATE NAMESPACE IF NOT EXISTS test;
CREATE DATABASE IF NOT EXISTS test;

4. 匹配surrealdb.js与SurrealDB版本

版本不兼容可能导致连接问题,建议安装与服务版本匹配的surrealdb.js:

npm uninstall surrealdb.js
npm install surrealdb.js

5. 切换到WebSocket端点

若HTTP RPC端点仍有问题,尝试使用WebSocket协议的端点:

await db.connect('ws://127.0.0.1:8000/rpc', {
    namespace: 'test',
    database: 'test',
    auth: {
        scope: 'user',
        username: 'root',
        password: 'root',
    },
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:55:27