I want to retrieve data from mongoDB, a collection of products, But instead of an array or an object with data, I get an HTML template. What can this be related to? The database is connected, I checked.
Screenshots below.
model product
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
title: String,
price: Number,
quantity: Number,
});
const Product = mongoose.model("products", productSchema);
module.exports = Product ;
server
const express = require('express');
const app = express();
const Product = require("./models/Products");
app.get("/api/products", (req, res) => {
Product.find((error, data) => {
if (!error) {
res.status(200).send(data);
} else {
res.status(500).send(error);
}
});
});
axios from the client side
import axios from "axios";
const axiosInstance = axios.create({
baseURL: 'http://localhost:8080',
});
export default axiosInstance;
client
useEffect(() => {
const fetchData = async () => {
const data = await axios.get("/api/products");
console.log('product >>>', data);
}
fetchData();
}, []);
mongoDB, collection product
screenshot
2
Answers
I found a solution to this problem. Model.find() no longer accepts callbacks, that's why the error occurs. It is enough to specify then after find, and everything will work
Model.find().then((data) => {}))
Axios baseURL was not set.
You can create an axiosInstance with baseURL and use it to call the api.