Home > Enterprise >  my api is returning invalid JSON nodejs in post request while fectching
my api is returning invalid JSON nodejs in post request while fectching

Time:07-15

I am sending a post request in my next js app API (API is for updating address)

this is my fetching API code

async function handleSubmit() {

const data = { deliveryAddress, landmark, pincode, district, block, state }
const userID = localStorage.getItem("userID")

for (let item in data) {
  let element = data[item];
  if (element == "") {
    toast.error(`${item} field must be filled`, {
      position: "top-center",
      autoClose: 3000,
      hideProgressBar: false,
      closeOnClick: true,
      pauseOnHover: true,
      draggable: true,
      progress: undefined
    });
    break;
  }

}
console.log("above try");
console.log({ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify( userID)) });
try {
  console.log("hello");
  let res = await fetch(`${process.env.NEXT_PUBLIC_HOST}/api/updateaddress`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]
  })
  let parsedResponse = await res.json()
  console.log("response", parsedResponse);
}
catch (error) {
  console.log(error)
}

}

and this code is returning an invalid Json error this code line body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]

this is what I got when I console.log my response body console.log({ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify( userID)) });

image of console error and the above-logged coder this is the console image of error and the above-logged code

Summary I am getting a invalid JSON error but i think my JSON is correct and nothing wrong with api

CodePudding user response:

I am getting a invalid JSON error

Well, your JSON is invalid…

body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]

That's an array, not JSON. You need to pass JSON to the body property.

Also JSON.parse(JSON.stringify(...)) does nothing useful in this context (since it is useful to deep clone simple objects and you don't mutate the value afterwards) so don't do that.

body: JSON.stringify([{ "address": data, "userid": userID }])

… but a 401 status means Unauthorized.

  • Related