Reputation: 408
Hi, my frontend is not reading JSON data sent by my backend, can you help: The backend is perfectly generating the JSON. But my react component is not able to consume the API.
Frontend:
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;
I am trying to fetch data from localhost:9000/employee but it is not reading .
Backend:
//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..."));
Upvotes: 2
Views: 51
Reputation: 1720
You are just making a request to '/employees' you need to provide the full url to fetch something like
localhost:/9000/employees
hope it helps
Upvotes: 1