I have an express server that is fetching data from a local MongoDB.
The fetching seems to work and I am able to log the fetched data:
app.get("/getTestData", async (req, res) => {
const data = await ContentDataSchema.find();
console.log(`Mongo data: ${data})`);
res.json(data);
});
This prints on the server console the correct data from DB which is expected to be an array of objects of the ContentDataSchema.
However, when trying to get this data from the client side:
useEffect(() => {
fetch("http://localhost:7007/getTestData")
.then((response) => {
console.log(`RESPONSE ${response.body}`)
})
.catch((error) => console.log(`SERVER ERROR ${error})`));
}, []);
Console output from this is RESPONSE [object ReadableStream]
And if I tried to to log console.log(RESPONSE ${JSON.stringify(response.body)})
Then the output is just {}.
Using Postman I can see the correct expected response calling the same endpoint.
Expected output on the client side would be the actual json from the DB.
To read the JSON response, you have to use the response.json() method. You can refer to the MDN docs about fetch to learn more about it.
fetch("http://localhost:7007/getTestData")
.then(response => response.json())
.then(data => console.log(data));
Related
enter image description here
I need to get data from this api endpoint, and send it to my client (React). Everything works fine between the frontend and backend, but I cant seem to figure out how to get the data within /dailyscores endpoint and send it using axios. Any help on why res.send is not a function inside .then, and a way to get it work?
The way you are using res as argument name for both express and axios callback is the issue here.
app.get('...', (req, res) => {
axios.get('...').then((res) => {
res.send(res.data); // here the res of axios.then is used
})
});
Instead use different names
app.get('...', (req, res) => {
axios.get('...').then((response) => {
res.send(response.data);
})
});
checkout variable scopes for more info
To get data from API please try as below:
const [apiResp, setApiResp] = useState([]);
useEffect(() => {
axios.get(`<api>`)
.then(res => {
const response = res.data;
setApiResp([response]);
})
});
I'm trying to fetch data from my mongoDB collection and send it back to the client in a response and for some reason the json I get as a response is always empty:
app.get("/users", bodyparser.json(), function(req, res) {
collection.find().toArray().then(dbresponse => {
console.log(dbresponse)
res.json(dbresponse);
console.log(res.json)
})
})
the dbresponse has all of the data I am looking to get, but res.json() doesn't seem to be writing anything to the response,
The client side looks like this:
fetch("/users")
.then(res => res.json)
.then(json => {
console.log(json)
Array.from(json).forEach(user => addUser(user.user, user.pass, user.id))
})
Thanks!
Client code should be fetch("/users").then(res => res.json()).
https://developer.mozilla.org/it/docs/Web/API/Fetch_API/Using_Fetch
I am using Node JS and MYSQL. When I add new data to my project, it writes to the database. Then when I want to GET this data with another API, it doesn't come. When I try again after about a minute, it comes on. However, right after I send a request via Swagger, data comes from the outside (Postman or Panel) on my request again.
My simple Controller.
exports.GetAll = (req, res, next) => {
ThisModel.GetAllSQL()
.then((response) => {
res.status(200).json(response[0]);
}).catch((error) => {
res.status(400).send();
console.log('Senaryo listesi çekilirken bir hata meydana geldi: ' + error);
})
}
.then((response) => {
res.status(200).json(response[0]);
})
Judging from the line above, it looks like you're getting a list/array of data, but only returning the first item in the list response[0].
Maybe this is what you're looking for:
.then((response) => {
res.status(200).json(response);
})
The Problem
I deployed a create-react-app webapp to aws ec2. It's used to display data from a database and send data to it. I use ExpressJS, CORS and MySQL.
With the following code i fetch the corresponding URL and the server.js sends back the database content. Until here, everything works fine.
getBets = _ => {
fetch("http://ec2***.amazonaws.com
.then(response => response.json())
.then(response => this.setState({bets: response.data}))
.catch(err => console.error(err))
};
The problem begins when sending data to the database with the following code:
addBet = _ => {
const { bet } = this.state;
fetch(`http://ec2***.amazonaws.com/bets/add?name=${bet.person_name}&bet=${bet.time_bet}`)
.then(response => response.json())
.then(this.getBets)
.catch(err => console.error(err))
};
On click the addBet-function populates the db, but in chrome I following error:
GET http://ec2***.amazonaws.com/bets/add?name=Peter%20Pan5&bet=10:17%205 net::ERR_EMPTY_RESPONSE
and
TypeError: Failed to fetch
Regarding chrome dev-tools, the first error corresponds to the fetch in the addBet function and the second error to the catch part.
On the server side I've the following code for processing the fetch:
app.get("/bets/add", (req, res) => {
const {name, bet} = req.query;
const INSERT_BET = `INSERT INTO bets (name, bet, timestamp) VALUES("${name}", "${bet}", CURTIME())`;
connection.query(INSERT_BET, (err, res) => {
if (err) {
return res.send(err);
}
else {
return res.send("succesfully added your bet");
}
})
});
I want to mention, that the res paramter in the app.get part is unused. That tells me my IDE.
After a lot of hours digging deeper in the topics of expressJS and the fetch api, I guess, that the app.get part doesn't send a response to the server. But the fetch need some response.
My Question
How do I have to change the code in the app.get part to send a proper response back to the server?
AND
Am I right with my guess?
In MYSQL when you do an insert query you get back err,results and fields in the callback function like this:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function (error,
results, fields) {
if (error) throw error;
console.log(results.insertId);
});
You have used the parameter res for result and then you have used res.send() which now corresponds to that res parameter in the callback function and not the res object.Rewrite it like this:
app.get("/bets/add", (req, res) => {
const {name, bet} = req.query;
const INSERT_BET = `INSERT INTO bets (name, bet, timestamp) VALUES(?,?,?)`;
connection.query(INSERT_BET,[name,bet,CURTIME()] ,(err, result) => {
if (err) {
return res.send(err);
}
else {
return res.send("succesfully added your bet");
}
})
});
I have also used prepared statement in place of normal sql queries. These are used to prevent sql injections. I hope it will work now.
I'm using a MongoDB, Node, Express and React.js. I'm not able to receive data from my node.js server to my react.js client. This is the error I have: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0. I know its a very common error but none of the solutions I found seems relevant for my context.
Here's the package.json line where my proxy is initialized:
"proxy": "http://localhost:5000",
Here's my express routing:
app.get('/main-data', (req, res) => {
MongoClient.connect(connectionURL, {
useNewUrlParser: true,
}, (error, client) => {
if(error){
return console.log("Unable to connect to the db.");
}
const db = client.db(databaseName);
db.collection("metadata_from_bot")
.find()
.toArray((error, data) => {
console.log(data);
res.json(data);
});
})
res.json({hello: "world"})
})
Here's my react fetch:
componentDidMount() {
fetch('/main-data')
.then(res => res.json())
.then(data => this.setState({ data }));
}
When I go to http://localhost:5000/main-data, I receive the following output:
When I inspect the network tab, here's what I have: Status Code: 304 Not Modified.
However, when I click on the link (http://localhost:3000/main-data) in the network-tab, I get the error.
The data should be set to the state but now I'm not able to receive it in JSON format.
I'm not sure but shouldn't you use host in fetch
componentDidMount() {
fetch('http://localhost:5000/main-data')
.then(res => res.json())
.then(data => this.setState({ data }));
}