skip to Main Content

I’m currently working on a web application that incorporates a chatbot feature. While developing, I’ve encountered a perplexing error related to the interaction between my frontend and backend components. Specifically, I’m getting the following error in my browser’s developer console upon pressing the submit button when placing in user input:

POST http://127.0.0.1:3000/predict 404 (Not Found)

This error appears to be connected to the way my frontend communicates with my backend, and I’m seeking guidance on how to address it effectively. Here’s a detailed breakdown of my setup:

Frontend (app.js):

import React, { useState, useEffect } from "react";
import "./style.css";

const Chatbox = () => {
  const [state, setState] = useState(false);
  const [messages, setMessages] = useState([]);

  const toggleState = (chatbox) => {
    setState(!state);

    // show or hide the box
    if (!state) {
      chatbox.classList.add("chatbox--active");
    } else {
      chatbox.classList.remove("chatbox--active");
    }
  };

  const onSendButton = (chatbox) => {
    var textField = chatbox.querySelector("input");
    let text1 = textField.value;
    if (text1 === "") {
      return;
    }

    let msg1 = { name: "User", message: text1 };
    setMessages((prevMessages) => [...prevMessages, msg1]);

    fetch("http://127.0.0.1:3000/predict", {
      method: "POST",
      body: JSON.stringify({ message: text1 }),
      mode: "cors",
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((r) => r.json())
      .then((r) => {
        let msg2 = { name: "Sam", message: r.answer };
        setMessages((prevMessages) => [...prevMessages, msg2]);
        updateChatText(chatbox);
        textField.value = "";
      })
      .catch((error) => {
        console.error("Error:", error);
        updateChatText(chatbox);
        textField.value = "";
      });
  };

  const updateChatText = (chatbox) => {
    var html = "";
    messages
      .slice()
      .reverse()
      .forEach(function (item, index) {
        if (item.name === "Sam") {
          html += `<div class="messages__item messages__item--visitor">${item.message}</div>`;
        } else {
          html += `<div class="messages__item messages__item--operator">${item.message}</div>`;
        }
      });

    const chatmessage = chatbox.querySelector(".chatbox__messages");
    chatmessage.innerHTML = html;
  };

  useEffect(() => {
    const openButton = document.querySelector(".chatbox__button");
    const chatBox = document.querySelector(".chatbox__support");
    const sendButton = document.querySelector(".send__button");
    const node = chatBox.querySelector("input");

    openButton.addEventListener("click", () => toggleState(chatBox));

    sendButton.addEventListener("click", () => onSendButton(chatBox));

    node.addEventListener("keyup", ({ key }) => {
      if (key === "Enter") {
        onSendButton(chatBox);
      }
    });
  }, []);

  return (
    <div className="chatbox">
      {/* Your chatbox HTML structure goes here */}
      <button className="chatbox__button">
        <img src="./images/chatbox-icon.svg" alt="Chat" />
      </button>
      <div className={`chatbox__support ${state ? "chatbox--active" : ""}`}>
        {/* Your chatbox support HTML structure goes here */}
        <div className="chatbox__header">
          {/* Your chatbox header HTML structure goes here */}
          <div className="chatbox__image--header">
            <img
              src="https://img.icons8.com/color/48/000000/circled-user-female-skin-type-5--v1.png"
              alt="User"
            />
          </div>
          <div className="chatbox__content--header">
            <h4 className="chatbox__heading--header">Chat support</h4>
            <p className="chatbox__description--header">
              Hi. My name is Sam. How can I help you?
            </p>
          </div>
        </div>
        <div className="chatbox__messages">
          {/* Your chatbox messages HTML structure goes here */}
          {messages.map((item, index) => (
            <div
              key={index}
              className={`messages__item messages__item--${
                item.name === "Sam" ? "visitor" : "operator"
              }`}
            >
              {item.message}
            </div>
          ))}
        </div>
        <div className="chatbox__footer">
          <input type="text" placeholder="Write a message..." />
          <button className="send__button">Send</button>
        </div>
      </div>
    </div>
  );
};

export default Chatbox;

Backend (app.py):

import sys
print("Python Interpreter Path:", sys.executable)

from flask import Flask, render_template, request, jsonify
from chat import get_response

app = Flask(__name__)

@app.route("/", methods=['GET'])
def index_get():
    return render_template("base.html")

@app.route("/predict", methods=['POST'])
def predict():
    text = request.get_json().get("message")
    # TO-DO: check if text is valid
    response = get_response(text)
    message = {"answer": response}
    return jsonify(message)

if __name__ == "__main__":
    app.run(debug=True, port=3000)

Here’s what I’ve tried and observed so far:

  • Server Is Running: I’ve verified that both my frontend and backend servers are running without any issues. My frontend is on http://localhost:3000, and my backend is on http://127.0.0.1:3000.

  • Network Request: The error occurs when my frontend attempts to make a POST request to my backend using the URL http://127.0.0.1:3000/predict. This is supposed to trigger a chatbot response.

  • JSON Parsing Issue: Additionally, I’m getting another error in the console: Error: SyntaxError: Unexpected token ‘<‘, "<!DOCTYPE "… is not valid JSON". This seems to indicate an issue with parsing the response as JSON.

Here are my questions:

  1. What could be causing the "404 (Not Found)" error when making the POST request to http://127.0.0.1:3000/predict?

  2. Could the "SyntaxError: Unexpected token ‘<‘" issue be related to how my backend responds to the POST request?

  3. Are there any common pitfalls or best practices when implementing communication between a React frontend and a Flask backend like this?

  4. I’m relatively new to web development, so any insights or debugging steps you can provide would be greatly appreciated. Thank you for your time and assistance!

2

Answers


  1. this cause what leaded to the question is that your request cross origin,and your decription abount the frontend and the backend in same port is wrong.

    Login or Signup to reply.
  2. Your frontend is on http://localhost:3000 and backend is on http://127.0.0.1:3000. Technically both are same. Frontend and backend can’t be run in same port number. This is the reason why you get 404 error on "/predict" because it will find a route in frontend not backend. You need to run the backend in different port number.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search