Home > OS >  When i am trying fetch api from node js it is not working
When i am trying fetch api from node js it is not working

Time:07-14

import React, { useCallback, useEffect, useState } from "react";
   import { v4 as uuidv4 } from "uuid";
   import { useAppContext } from "./context/appContext";
   import Video from "twilio-video";
   import Room from "./components/Room/Room";
   import { Home, Header } from "./components/index";

   app.post("/video/token", (req, res) => {
     const identity = req.body.identity;
     const room = req.body.room;
     const token = videoToken(identity, room, config);
     sendTokenResponse(token, res);
   });

In the above section i made api endpoint in node js /video/token but when i fetch it in React js it's give an error

const data = await fetch("/video/token", {
      method: "POST",
      body: JSON.stringify({
        identity: username,
        room: roomName,
      }),
      headers: {
        "Content-Type": "application/json",
      },
    }).then((res) => res.json());

And the above code is fetching the api and it is returning Promise Unexpected token < at JSON position 0

import React, { useCallback, useEffect, useState } from "react";
   import { v4 as uuidv4 } from "uuid";
   import { useAppContext } from "./context/appContext";
   import Video from "twilio-video";
   import Room from "./components/Room/Room";
   import { Home, Header } from "./components/index";

   app.post("/video/token", (req, res) => {
     const identity = req.body.identity;
     const room = req.body.room;
     const token = videoToken(identity, room, config);
     sendTokenResponse(token, res);
   });

CodePudding user response:

You should use async and await together, not only await

async function sendData(){
    await fetch("/video/token", {
      method: "POST",
      body: JSON.stringify({
        identity: username,
        room: roomName,
      }),
      headers: {
        "Content-Type": "application/json",
      },
    }).then((res) => res.json());
}

CodePudding user response:

this happens because you are trying to parse api response as json which is not a json

res.json()

here you should first check api response if its json or not.

  • Related