#Backend returns undefined

55 messages · Page 1 of 1 (latest)

hot kettle
#

Frontend:

  const onDelete = async (linkId) => {
    console.log(linkId) // 644aad3188836e6180f5fa05
    const res = await fetch("/api/links", {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${localStorage.getItem("token")}`,
      },
      body: JSON.stringify({ linkId }),
    });

    if (res.status === 200) {
      const updatedLinks = await res.json();
      setLinks(updatedLinks);
    } else {
      alert("Error deleting link");
    }
  };

Backend

else if (req.method === "DELETE") {
    try {
      const user = await authMiddleware(req, res);
      const { linkId } = req.body;
      console.log(linkId) // undefined

      if (req.headers["content-type"] !== "application/json") {
        res.status(400).json({ msg: "Invalid content type" });
        return;
      }

      const linkIndex = user.links.findIndex((link) => link._id.toString() === linkId);

      if (linkIndex !== -1) {
        user.links.splice(linkIndex, 1);
        await user.save();
        res.status(200).json(user.links);
      } else {
        res.status(404).json({ msg: "Link not found" });
      }
    } catch (error) {
      console.error(error);
      res.status(500).json({ msg: "Server error" });
    }
  }
#

I'm literally just trying to send a string to the backend

#

i fixed it

#

wtf

#

what a dumb fix

native steeple
#

what was it? bighmm

hot kettle
#

I changed it to a POST request

#

And included a fake method: "DELETE" in the req body

#

I guess the delete method can't carry data?

#

wtf

native steeple
#

I think this is because in the spec the delete method isn't supposed to have a body

#

so next is not parsing it

hot kettle
#

Hmm is it set up to use queries?

native steeple
hot kettle
open yarrow
#

I can't recreate this issue, it may be a formatting issue?

// /pages/deleteme/index.js
import { useState } from "react"

export default function DeleteMe(){
    const [data, setData] = useState(null)
    const [isLoading, setLoading] = useState(false)

    const linkId = {
        something: {
            else: 'hello world'
        }
    }

    const send = async () => {
        fetch('/api/delete', {
            method: "DELETE",
            body: JSON.stringify({ linkId }),
          })
            .then((res) => res.json())
            .then((data) => {
              setData(data)
              setLoading(false)
            })
    }
    return(<div>
        <p>{JSON.stringify(data)}</p>
        <button onClick={send}>Delete</button>
    </div>)
}
// /pages/api/delete.js
export default function handler(req, res){
    if(req.method === 'DELETE'){
        console.log(req.body)
        res.send({hello: 'world'})
    }
}
hot kettle
#

bro what

#

ive spent 4 hours on this

#

and yours just works

#

WHY

native steeple
#

maybe it is the authMiddleware modifying the request?

open yarrow
#

but it'll accept it anyway

hot kettle
#

Wanna see it?

#

It is kinda small

#

Nothing should be interfering

open yarrow
#

can you run next lint

#

long shot but lol

#

or if you can send just those 2 files

native steeple
#

you can comment the line to test it

hot kettle
#

authMiddleware

const jwt = require("jsonwebtoken");
const User = require("../models/User");

module.exports = async function (req, res) {
  const token = req.headers.authorization ? req.headers.authorization.split(" ")[1] : null;

  if (!token) {
    res.status(401).json({ msg: "No token, authorization denied" });
    return;
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const user = await User.findById(decoded.user.id);
    if (!user) {
      res.status(401).json({ msg: "Invalid token" });
      return;
    }
    return user;
  } catch (error) {
    res.status(401).json({ msg: "Invalid token" });
  }
};
native steeple
#

usually in these situations I just comment the code until it works again so you have some idea of what might be causing the issue

hot kettle
open yarrow
#

also enabling debugging helps

hot kettle
#

and it was returning undefined

#

Ty for the help. Got off work coding, got home, been coding ever since

#

it is now midnight

#

im never using the delete method again

open yarrow
#

if you add this to .vscode/launch.json I would try adding some breakpoints later to figure out what it's doing

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Next.js: debug server-side",
      "type": "node-terminal",
      "request": "launch",
      "command": "npm run dev"
    },
    {
      "name": "Next.js: debug client-side",
      "type": "chrome",
      "request": "launch",
      "url": "http://localhost:3000"
    },
    {
      "name": "Next.js: debug full stack",
      "type": "node-terminal",
      "request": "launch",
      "command": "npm run dev",
      "serverReadyAction": {
        "pattern": "started server on .+, url: (https?://.+)",
        "uriFormat": "%s",
        "action": "debugWithChrome"
      }
    }
  ]
}
hot kettle
#

If i get another impossible issue, i will certainly do that

#

ty

open yarrow
#

it's kinda my hail mary if something really weird is happening 😂

hot kettle
#

im still somewhat new to next

#

just when i got too comfortable with react

#

next has been rocking my world lol

open yarrow
#

tbf - next is weird. I had to unlearn a lot of bad habits from old packages and less is usually more lol. The rest is just templating.

open yarrow
hot kettle
#

Just what I needed

#

Except...not right now

#

Bed time lmao

#

Bookmarked, ty ty