简体   繁体   English

将 Express 后端数据从数据库发送到 React 前端

[英]Sending Express back-end data from a database to React front end

I'm trying to show some information about a user in front-end, but I don't know why is not showing anything.我试图在前端显示有关用户的一些信息,但我不知道为什么没有显示任何内容。 If I access the server using localhost:8080/api/user I can see the information in an empty page (is just a dummy database that I had), but I can't print them in my content page, my code recognizes the list as being empty.如果我使用localhost:8080/api/user访问服务器,我可以在一个空页面中看到信息(只是我拥有的一个虚拟数据库),但我无法在我的内容页面中打印它们,我的代码会识别列表作为空。 I'm a beginner and I just started using React, Node.js, and Express.我是初学者,刚开始使用 React、Node.js 和 Express。

UserStatus.js用户状态.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服务器.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);
});

To debug you can set breakpoints or use console.log or some other console method.要调试,您可以设置断点或使用 console.log 或其他一些控制台方法。 First you can check your fetch response:首先,您可以检查您的 fetch 响应:

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
 }

Also you should catch errors.你也应该捕捉错误。 It seems to me you are returning a dataset with a toplevel 'recordset' attribute.在我看来,您正在返回一个具有顶级“记录集”属性的数据集。 So you probably have to do: return res.json().recordset所以你可能必须这样做:返回 res.json().recordset

First of all, list.length is just a number you need to check if the array is greater than zero首先,list.length 只是一个数字,您需要检查数组是否大于零

list.length > 0 

Secondly, Check to see if the data is being received from the backend其次,检查是否正在从后端接收数据

   getList = async () => {
    try{
     let res =  await fetch('/api/user');
     console.log(res);
    } catch (err) {
     console.log(err);
    }        
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM