Привет, мой интерфейс не читает данные JSON, отправленные моим бэкэндом, вы можете помочь: бэкэнд прекрасно генерирует JSON. Но мой компонент реагирования не может использовать 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..."));