【发布时间】:2021-06-30 22:52:12
【问题描述】:
API 在浏览器以及 Google Postman 从数据库中返回数据时运行良好,但是当我尝试从我的 react JS 应用程序访问它时,它给了我空响应的错误 这是API代码
//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);
}
}
这是model.js文件
//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();
});
});
}
这是在 react js 文件中
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);
}
(当我使用来自 json 文件的数据但不适用于数据库数据时,它可以工作)
【问题讨论】:
标签: javascript node.js reactjs api