我无法在react

时间:2019-10-02 18:06:16

标签: reactjs express

您好,我的前端未读取我的后端发送的JSON数据,您可以帮忙吗: 后端完美地生成了JSON。但是我的react组件无法使用该API。

前端

import React from 'react';
import './App.css';

class App extends React.Component {
  state={
    users:[]
  };



  componentDidMount() {
    fetch('/employees')
      .then(res => {
          return res.json()
       })
      .then(data => {  
          this.setState({ users:data })
       })
       .catch(function (error) {
        console.log(error);});
   }

  render(){
    return(
      <div>
        {this.state.users.map(user =>
                <div key={user.id}>user: {user.name} Salary: {user.salary}</div>
              )}
      </div>
    )
  }
}

export default App;

我正在尝试从localhost:9000 / employee中获取数据,但未读取。

后端:

//Step1:    import mongodb module
var mongodb = require("mongodb");

//Step2:    Create client for mongodb
var mongoClient = mongodb.MongoClient;

//Step3:    Define url with mongodb path
var url = "mongodb://localhost:27017/Employee";

var app = require("express")();
var bodyParser = require('body-parser')

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/employees',function(req,resp){
    mongoClient.connect(url,function(err,db){
        if ( !err){
            var collection = db.collection("lcdEmployees");
            var cursor = collection.find().toArray(function(err,records){
                if ( !err )
                    resp.send(records);
            });
        }
    });
});
app.listen(9000,()=>console.log("API with db access started listening..."));

1 个答案:

答案 0 :(得分:1)

您只是向'/ employees'请求,您需要提供完整的url以进行提取 像

localhost:/9000/employees

希望有帮助