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

JavaScript Fetch请求遇TypeError:无法读取undefined的'data'属性

问题:Fetch请求"/users/add"时出现TypeError:Cannot read property 'data' of undefined

使用JavaScript向"/users/add"发起Fetch请求时触发TypeError,错误信息为Cannot read property 'data' of undefined (reading 'data') at register:38:66。获取API密钥的第一个请求可正常运行,但第二个使用该密钥的"/users/add"请求报错,怀疑响应不含"data"属性,打印响应至控制台仍未明确原因。

前端JavaScript代码

let apiKey = null;

fetch("/api-key", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  }
})
  .then(response => response.json())
  .then(data => apiKey = data)
  .catch(error => console.error(error));

function register() {
  let user = document.getElementById("user").value;
  let pass = document.getElementById("pass").value;

  // Post request to /users/add using the API key
  fetch("/users/add", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": apiKey
    },
    body: JSON.stringify({
      username: user,
      password: pass,
      api_key: apiKey
    })
  })
    .then(response => {
      console.log("Request JSON data:", JSON.parse(response.config.data));
      if (!response.ok) {
        throw new Error("Failed to add user. Response status: " + response.status);
      }
      return response.json();
    })
    .then(data => {
      console.log("User added successfully:", data);
    })
    .catch(error => {
      console.error("Error adding user:", error);
    });
}

后端Node.js代码

router.route('/add').post((req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    const api_key = req.body.api_key;

    bcrypt.hash(password, 10, (err, hashedPassword) => {
        if (api_key != real_api_key) {
            return res.status(400).json('Error: Incorrect API key');
        }

        if (err) {
            return res.status(400).json('Error: ' + err);
        }

        const newUser = new User({username, password: hashedPassword, api_key});

        newUser.save()
            .then(() => res.json('User added!'))
            .catch(err => res.status(400).json('Error: ' + err));
    });
});

错误根源

报错行是console.log("Request JSON data:", JSON.parse(response.config.data));,Fetch API的Response对象不存在config属性——你混淆了Fetch和Axios的API规范:Axios的响应对象会包含config字段存储请求配置,但Fetch的Response仅提供ok、status、json()等原生方法和属性,因此response.config为undefined,读取response.config.data自然触发Cannot read property 'data' of undefined错误。

解决步骤

  1. 移除错误的日志打印行,若要查看请求体内容,可在调用fetch前直接打印:
const requestBody = JSON.stringify({
  username: user,
  password: pass,
  api_key: apiKey
});
console.log("Request JSON data:", requestBody);

// 后续fetch的body参数传入requestBody
fetch("/users/add", {
  // ...其他配置
  body: requestBody
})
  1. 额外优化:获取API密钥的请求是异步操作,若用户在apiKey未赋值完成时点击注册,会导致apiKey为null,触发后端API密钥校验错误。可在注册函数中先判断apiKey是否存在:
function register() {
  if (!apiKey) {
    console.error("API密钥尚未获取完成");
    return;
  }
  // ...后续注册逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:05:17