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

如何在Vue.js中使用fetch() API更新Directus集合数据?

解决Vue.js中用fetch更新Directus集合数据的问题

你的代码核心问题是缺少必要的请求头,且未处理响应与错误逻辑。Directus的API对请求格式、认证有明确要求,以下是修正后的完整实现:

修正后的代码示例

async updateCustomerName() {
  try {
    const apiUrl = `http://localhost:8055/items/customers/${this.$route.params.id}`;
    
    const response = await fetch(apiUrl, {
      method: 'PATCH', // Directus更新单条数据必须用PATCH,POST用于创建新条目
      headers: {
        'Content-Type': 'application/json', // 必填,告知API请求体为JSON格式
        // 权限验证:若Directus开启权限控制,需携带认证Token
        'Authorization': `Bearer ${localStorage.getItem('directus_token')}`
        // 测试环境可改用静态Token:'Authorization': 'Bearer 你的静态Token内容'
      },
      body: JSON.stringify({
        name: this.name
      })
    });

    // 校验请求是否成功
    if (!response.ok) {
      const errorInfo = await response.json();
      throw new Error(errorInfo.message || '更新客户名称失败');
    }

    const updatedResult = await response.json();
    console.log('更新成功:', updatedResult);
    // 此处可添加成功后的操作,比如提示用户、刷新数据列表等
  } catch (error) {
    console.error('更新出错:', error.message);
    // 处理错误,比如给用户显示错误提示
  }
}

关键注意事项

  • 请求方法:更新单条数据必须使用PATCH,POST是创建新条目的方法,因此你之前用POST无效是正常情况。
  • 请求头要求:
    • Content-Type: application/json是必填项,否则Directus无法正确解析请求体。
    • Authorization头:如果你的Directus实例未开放公开写权限,必须携带用户或服务账户的Token,格式为Bearer [Token值]。
  • 响应与错误处理:通过response.ok判断请求是否成功(HTTP状态码200-299),失败时解析API返回的错误详情,便于定位问题;用try/catch捕获网络异常或业务错误,避免程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:20:29