同时发送 POST/GET 请求时出现问题 - Nuxt 3

问题描述 投票:0回答:1

现在我希望通过发送用户的姓名并接收与该用户相关的所有最后一个项目来从数据库加载用户的最后一个项目。由于某种原因,每次我尝试执行此操作时,我都会收到“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()
  }
});

那么这段代码到底有什么问题呢?

我尝试将 .get/.post 添加到文件名并对请求代码结构进行一些编辑,但没有成功。

vue.js vuejs3 nuxt.js nitro
1个回答
0
投票

我认为

 new MongoClient(uri...
有错字,应该是
new MongoClient(url...

我认为你还应该在

 const db = client.db();

中指定数据库
© www.soinside.com 2019 - 2024. All rights reserved.