0

I am having trouble sending an object to my dynamic api route in Next. Sending a regular string works fine and I am able to update my MongoDB without issue. When sending the object though the request data just shows up as [object Object].

This is the current code snippet:

Client Side

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 Route: /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);
}
code_dough
  • 97
  • 1
  • 7
  • Normally, data is sent as _payload_ of a POST request - for data to be added to the database. – prasad_ Jan 04 '22 at 16:40
  • 1
    @juliomalves Yes this solves the issue. I was misunderstanding the use case for Dynamic API routes within Next. Setting up a basic POST request using fetch and changing the backend api to a standard static route was the right way. – code_dough Jan 07 '22 at 15:12

2 Answers2

2

consider 2 steps first send data through post request, then specify the content type through fetch request. see the example:

      const req = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: formData.get("email"),
        password: formData.get("password"),
      }),
    });
Paiman Rasoli
  • 1,088
  • 1
  • 5
  • 15
2

So this was a case of me misunderstanding when to use Dynamic API routes within next. Below is the correct implementation of what I was trying to do, which is just a basic POST request using fetch as others mentioned here.

Client:

// 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 Route:

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);
}
code_dough
  • 97
  • 1
  • 7