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

Nuxt 3中POST请求/api/lastProject出现500内部服务器错误排查

问题分析:500内部服务器错误排查

我希望通过传入用户名从数据库加载该用户的最新项目,但每次尝试时都会收到“Uncaught (in promise) FetchError: [POST] "/api/lastProject": 500 Internal Server Error”错误。

前端代码

let lastProjects = ref(null);
async function getLastProjects () {
  const { response } = await $fetch('/api/lastProject'
    , {
    method: 'post',
    body: {
      identity: data._value.name 
    },
    headers: { 'Content-Type': 'application/json' },
  }
  )

  console.log('response: ', response)

     if (!response) {
       throw new Error('Response is undefined');
    }

  lastProjects.value = response;
  return lastProjects;
}

onMounted(async () => {
    await getLastProjects()
});

后端代码(/api/lastProject.post.ts)

import { MongoClient } from 'mongodb';

export default defineEventHandler(async (event) => {
  try {
  const identity = await readBody(event);

  const url = process.env.MONGODB_URI;
if(!url) {
  throw createError({
    status: 400,
    message: "there is an error with the url"
  });
}

const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
  await client.connect();
  const db = client.db();
  const collection = db.collection('topicalMapsData');

  const users = await collection.findOne({ identity });

  if (!users) {
    throw new Error('User not found');
  }

  return users;
  } catch(err){
    throw new Error('Error: ', err);
  }
  finally {
    await client.close()
  }
});

具体问题点

  • 后端变量名不匹配:定义了url = process.env.MONGODB_URI,但创建MongoClient时使用的是未定义的uri变量,直接触发ReferenceError,导致500错误。
  • 请求body读取错误:后端const identity = await readBody(event);读取到的是完整请求body对象({ identity: 用户名 }),而非identity字段值,导致数据库查询条件错误。应改为const { identity } = await readBody(event);。
  • finally块变量作用域问题:client在try块内部声明,finally块无法访问,会抛出client is not defined错误。需将client声明提升到try块外部。
  • catch块错误处理无效:throw new Error('Error: ', err);无法正确传递错误信息,第二个参数会被忽略,无法定位具体问题。应改为throw new Error(Error: ${err.message});或直接抛出原错误。
  • 前端$fetch解构错误:$fetch直接返回响应数据,无需解构response属性,const { response } = await $fetch(...)会导致response为undefined,触发前端报错。应改为const response = await $fetch(...);。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:58:42