0

Before this, I have made React-based apps and for using any backend services (I use node js) I need to make a fetch request to that particular end-point eg: fetch("http://localhost:3000/api/myroutename").... but when I am trying this with simple html and js its not working its showing me this error (TypeError: Failed to fetch at HTMLDocument). But when I am rendering the html page server side then its working can someone explain me why.

Adding the HTML and backend code the api call i have made is in the script tag

const path = require("path");
const express = require("express");

const app = express();


const testRoute = require(__dirname + "/routes/test");

const port = 5000;

app.use("/api", testRoute);

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "index.html"));
});   //Not able to make api calls without this


app.listen(port, () => {
  console.log(`Server is up and running at port ${port}`);
});


//Test controller

exports.testGet = (req, res) => {
  return res.json({
    name: "Ayush",
    email: "a@email.com",
  });
};

exports.test = (req, res) => {
  console.log(req.body);

  return res.json({
    Result: "API request received successfully",
  });
};

// Test Route
const express = require("express");
const router = express.Router();

const { test, testGet } = require("../controller/test");

router.post("/test", test);
router.get("/testget", testGet);
module.exports = router;
  <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Client Test</title>
      </head>

      <body>
          <form>
            <div class="container">
                <h1>POST Form</h1>
                </h1>
                <form>
                  <label>email</label>
                  <input id="text1" type="text" />
                  <label>password</label>
                  <input id="text2" type="text" />
                  <input type="submit" value="Add"/>
                </form>
                <div class="result">Click Add!</div>
              </div> 
          </form>
      </body>
      <script>
    const sendData = (e) => {
        e.preventDefault();
        const text1 = document.querySelector("#text1").value
        const text2 = document.querySelector("#text2").value
        console.log(text1,text2);
        const user  = {
            email:text1,
            password:text2
        }
        fetch("http://localhost:5000/api/test",{
            method: "POST",
            headers:{
                Accept: "application/json",
                "Content-type":"application/json"
            },
            body: JSON.stringify(user),
        })
        .then((response) => {
         return response.json();
        })
        .then(data => console.log(data))
        .catch((err) => {
          console.log(err);
        });
     
    }
        document.addEventListener("submit", sendData);
        fetch("http://localhost:5000/api/testget",{
        method:"get"
    })    .then(res => res.json())
        .then(data => console.log(data))
        .catch(err => console.log("This is the error",err))
    </script>
    </html>

0 Answers0