简体   繁体   中英

API gives error (net::ERR_EMPTY_RESPONSE)

API works well in browser as well as Google Postman returns data from database but when I try to access it from my react JS application it gives me error of empty response here is API code

//Server.js
if (req.url === "/all" && req.method === "GET") {
    getAllUsers(req, res);
//Controller.js
async function getAllUsers(req, res) {
  try {
    const users = await dbData.findAllUsers();
    if (!users) {
      res.writeHead(400, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ message: "user not found" }));
    } else {
      res.writeHead(200, { "Content-Type": "application/json" });
     res.end(JSON.stringify(users));
    }
  } catch (err) {
    console.log(err);
  }
}

This is model.js file

//Model.js
function findAllUsers() {
  return new Promise((resolve, reject) => {
    con
      .connect()
      .then(() => {
        req
          .query(`select * from users`)
          .then((records) => {
            console.log(records);
            resolve(records);
            con.close();
          })
          .catch((err) => {
            console.log(err);
            con.close();
          });
      })
      .catch((err) => {
        console.log(err);
        con.close();
      });
  });
}

this is in react js file

async componentDidMount() {
    const response = await fetch("http://localhost:5000/all", {
      method: "GET",
      headers: {
        "content-Type": "application/json",
        cors: "no-cors",
      }
    });
    const data = await response.json();
    console.log("Data : ", data);
  }

(it is working when I use data from a json file but not working for database data)

I'm not sure what's going on here, but why are you sending cors: "no-cors" ?

Try supporting CORS on your server, install the npm package here . And add this to your server and see what happens.

const cors = require('cors');
app.use(cors());

And also, you don't need this:

res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "user not found" }));

You can just:

res.json({ message: "user not found" });

In fact, this might be what's causing the problem.

Problem Solved by just putting ACAO(Access-Control-Allow-Origin) header and set it to origin address where I was sending request.

res.writeHead(400, { "Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:1234",
 });

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