Search code examples
javascriptnode.jsreactjsfetch

using of fetch API the unexpected end of input error occurr in login fuction


I try using the fetch data from localhost

Backend Working fine when i try to fetch data from frontend look like server is not giving respons

    let headersList = {
      Accept: "*/*",
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*"
    };

    let bodyContent = JSON.stringify({
      email: loginData.email,
      passwd: loginData.passwd,
    });

    let response = await fetch("http://localhost:2000/api/auth/login", {
      method: "POST",
      headers: headersList,
      mode: "cors",
      body: bodyContent
    });
    let data = await response.json();
    console.log(data);

I understand that this is because I am trying to fetch that data from within my localhost and the solution should be using Cross-Origin Resource Sharing (CORS). I thought I actually did that, but somehow it either ignores what I write in the header or the problem is something else

I have try but it's not work

mode: "no-cors"


Solution

  • I FACED THE SAME PRBOBLEM AND THIS SAVED MY LIFE
    add this to your backend app.js file

    //install cors package: npm i cors
    const cors = require('cors')
    
    // add this at the head of your code
    app.use(cors({
            //your localhost address
    origin: 'http://localhost:3000'
    }))