如何通过fetch()将对象发送到Next.js中的动态api路由



在Next中将对象发送到我的动态api路由时遇到问题。发送一个常规字符串很好,我可以毫无问题地更新我的MongoDB。当发送对象时,请求数据只显示为[object object]。

这是当前的代码片段:

客户端

let bookData = {
title: data[i].title,
author: data[i].author,
date: data[i].date,
isbn: data[i].isbn,
description: data[i].description,
image: data[i].image
}
fetch(`/api/db/saveBook/${bookData}`);

API路由:/pages/API/db/saveBook/[book].js

import { MongoClient } from "mongodb";
export default async function handler(req, res) {
const book = req.query;
const client = await MongoClient.connect(process.env.MONGODB_URI);
const db = client.db();
const collection = db.collection('books');

const addBook = await collection.insertOne(book);
client.close();
res.json(addBook);
}

考虑两个步骤:首先通过post请求发送数据,然后通过fetch请求指定内容类型。参见示例:

const req = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: formData.get("email"),
password: formData.get("password"),
}),
});

所以这是我误解在next中何时使用动态API路由的一个例子。下面是我尝试做的事情的正确实现,这只是一个使用fetch的基本POST请求,就像这里提到的其他请求一样。

客户:

// Store book data to be sent to API route
let bookData = {
title: data[i].title,
author: data[i].author,
date: data[i].date,
isbn: data[i].isbn,
description: data[i].description,
image: data[i].image
}
// Send the book data to the backend API to be saved
fetch('/api/db/saveBook', 
{
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(bookData),
}
);

API路线:

import { MongoClient } from "mongodb";
export default async function handler(req, res) {
const book = req.body;
const client = await MongoClient.connect(process.env.MONGODB_URI);
const db = client.db();
const collection = db.collection('books');

const addBook = await collection.insertOne(book);
client.close();
res.json(addBook);
}

最新更新