简体   繁体   中英

Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in React js

I have spent many hours to solve that error or also see othersites to solve that but no solution found so I need help for solve that error

Screenshort here - https://i.stack.imgur.com/XbBJ5.jpg

I use https://www.twilio.com/blog/video-chat-react-hooks for create video app becuase of that above error I have not enter into the room

Here is the code below.

import React, { useState, useCallback } from "react";
import Lobby from "./Lobby";
import Room from "./Room";
const VideoChat = () => {
  const [username, setUsername] = useState("");
  const [roomName, setRoomName] = useState("");
  const [token, setToken] = useState(null);

  const handleUsernameChange = useCallback((event) => {
    setUsername(event.target.value);
  }, []);

  const handleRoomNameChange = useCallback((event) => {
    setRoomName(event.target.value);
  }, []);

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = fetch("/video/token", {
      method: "POST",
      body: JSON.stringify({
        identity: username,
        room: roomName,
      }),
      headers: {
        "Content-Type": "application/json",
      },
    }).then((res) => res.json());
    setToken(data.token);
  };
  const handleLogout = useCallback((event) => {
    setToken(null);
  }, []);

  let render;
  if (token) {
    render = (
      <Room roomName={roomName} token={token} handleLogout={handleLogout} />
    );
  } else {
    render = (
      <Lobby
        username={username}
        roomName={roomName}
        handleUsernameChange={handleUsernameChange}
        handleRoomNameChange={handleRoomNameChange}
        handleSubmit={handleSubmit}
      />
    );
  }

  return render;
};

export default VideoChat;

Twilio developer evangelist here.

As epascarello pointed out, when you make the request to get the token you are receiving a 404 response.

When you run this application, you need to start both the client side application and the server. To do this you should run

npm run dev

When you run npm start it will only run the React application, the server application won't run and you will get 404 responses when making requests to it. This is all based on my blog post oncreating a React application with a proxy to an Express server in which you can see the details of how this is set up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM