现在我希望通过发送用户的姓名并接收与该用户相关的所有最后一个项目来从数据库加载用户的最后一个项目。由于某种原因,每次我尝试执行此操作时,我都会收到“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 添加到文件名并对请求代码结构进行一些编辑,但没有成功。
我认为
new MongoClient(uri...
有错字,应该是new MongoClient(url...
我认为你还应该在
const db = client.db();
中指定数据库