我试图在前端显示一些有关用户的信息,但我不知道为什么不显示任何信息。如果我使用localhost:8080/api/user
访问服务器,则可以在empty page(只是我的虚拟数据库)中看到信息,但是无法在内容页面中打印它们,因此我的代码可以识别列为空。
我是一个初学者,我刚开始使用React,Node.js和Express。
UserStatus.js
import React from 'react';
class UserStatus extends React.Component {
constructor(props){
super(props);
this.state = {
list: []
}
}
// Fetch the list on first mount
componentDidMount() {
}
// Retrieves the list of items from the Express app
getList = () => {
fetch('/api/user')
.then(res => res.json())
.then(list => this.setState({ list })
)
}
render() {
const { list } = this.state;
return (
<div className="App">
<h1>User Status</h1>
{/* Check to see if any items are found*/}
{list.length ? (
<div>
{/* Render the list of items */}
{list.map((item) => {
return(
<div>
{item}
</div>
);
})}
</div>
) : (
<div>
<h2>No List Users Found</h2>
</div>
)
}
</div>
);
}
}
export default UserStatus
server.js
//Initiallising node modules
var express = require("express");
var bodyParser = require("body-parser");
var sql = require("mssql");
var app = express();
// Body Parser Middleware
app.use(bodyParser.json());
//CORS Middleware
app.use(function (req, res, next) {
//Enabling CORS
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
next();
});
//Setting up server
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
//Initiallising connection string
var dbConfig = {
user: '---',
password: '---',
server: '----',
database: '---'
};
//Function to connect to database and execute query
var executeQuery = function (query, res) {
sql.connect(dbConfig, function (err) {
if (err) {
console.log("Error while connecting database :- " + err);
res.send(err);
} else {
// create Request object
var request = new sql.Request();
// query to the database
request.query(query, function (err, ress) {
if (err) {
console.log("Error while querying database :- " + err);
res.send(err);
} else {
res.json(ress);
}
});
}
});
}
//GET API
app.get("/api/user", function (req, res) {
var query = "select * from Machine";
executeQuery(query, res);
});
//POST API
app.post("/api/user", function (req, res) {
var query = "INSERT INTO [user] (Name,Email,Password) VALUES (req.body.Name,req.body.Email,req.body.Password)";
executeQuery(res, query);
});
//PUT API
app.put("/api/user/:id", function (req, res) {
var query = "UPDATE [user] SET Name= " + req.body.Name + " , Email= " + req.body.Email + " WHERE Id= " + req.params.id;
executeQuery(res, query);
});
// DELETE API
app.delete("/api/user /:id", function (req, res) {
var query = "DELETE FROM [user] WHERE Id=" + req.params.id;
executeQuery(res, query);
});
答案 0 :(得分:2)
要调试,您可以设置断点或使用console.log或其他控制台方法。首先,您可以检查您的提取响应:
getList = () => {
fetch('/api/user')
.then(res => {
console.log(res) // is it a string or is it already json? What is the data structure?
return res.json()
})
.then(list => this.setState({ list }))
.catch(err => console.error(err)) // you should handle errors
}
另外,您应该捕获错误。在我看来,您正在返回具有顶级“ recordset”属性的数据集。因此,您可能必须做:返回res.json()。recordset
答案 1 :(得分:0)
首先,list.length只是您需要检查数组是否大于零的数字
list.length > 0
第二,检查是否从后端接收数据
getList = async () => {
try{
let res = await fetch('/api/user');
console.log(res);
} catch (err) {
console.log(err);
}
}