I have everything setup and see that I'm connecting successfully, but when trying to use the data in the collection, nothing is there.
server.js
const express = require('express');
const connectDB = require('./config/db');
const app = express();
connectDB();
app.get('/', (req, res) => res.send('API Running'));
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*'); // update to match the domain you will make the request from
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
app.use(express.json({ extended: false }));
app.use('/api/skateboard_tricks', require('./src/api/skateboard_tricks'));
app.use(
'/api/general_skate_data/trick_type',
require('./src/api/general_skate_data')
);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server started on port: ${PORT}`);
});
config/db.js
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
console.log('MongoDB connected...');
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;
src/api/skateboard_tricks.js
const express = require('express');
const router = express.Router();
const skate_tricks = require('../models/SkateTrick');
// @route GET api/skateboard_tricks
// @desc skateboard tricks data
// @access public
router.get('/', (req, res) => {
skate_tricks.find({}, (err, result) => {
if (err) {
res.send(err);
} else {
const trick_list = result[0];
res.send(trick_list.tricks);
}
});
});
module.exports = router;
API call in the app
const [trickList, setTrickList] = useState([]);
const [loading, setLoading] = useState(false);
const sfsApiCall = axios.create({
baseURL: 'http://localhost:5000/',
});
const getTrickData = async () => {
try {
const data = await sfsApiCall.get('api/skateboard_tricks').then((res) => {
console.log(res);
setTrickList(res.data);
});
setLoading(true);
} catch (err) {
console.error(err.message);
}
};
useEffect(() => {
getTrickData();
}, [loading]);
This used to work a while back and I'm revisiting the code now and it's not working anymore. Not sure what happened tbh.
Postman screenshot: https://i.stack.imgur.com/gIcok.png
Thanks in advance!
EDIT: I created a separate app to isolate the API connection files and it looks like I'm getting a network error. This is from Postman:
GET http://localhost:5000/api/skateboard_tricks
Error: read ECONNRESET
Request Headers
User-Agent: PostmanRuntime/7.28.4
Accept: */*
Postman-Token: 9da940c6-62bc-437e-bb07-d0457368264a
Host: localhost:5000
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
This error is showing in the console
GET http://localhost:5000/api/skateboard_tricks net::ERR_CONNECTION_REFUSED 200
This might be a CORS issue, but even troubleshooting that isn't clear to me. Hope this can help someone help me.
CodePudding user response:
If you are testing this locally, you can use some browser extensions to disable CORS restrictions:
For Chrome, https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en
For Firefox, https://addons.mozilla.org/en-US/firefox/addon/cors-unblock/
For Safari, you can check
Develop > Disable Cross-Origin Restrictions
These extensions will help you disable CORS entirely and you can sanely check if the API is returning data the way you expect it.
Note that this is purely for development and testing purposes. You should set up your API with the correct CORS configuration and then pass along the right headers in your request from the UI.
See: http://expressjs.com/en/resources/middleware/cors.html
CodePudding user response:
OK, so for whatever reason, I was no longer able to get the data from the trick object in the skateboard_tricks.js file. I had to specify the trick object when calling the function to pull the data in my app (see OP for comparison).
const express = require('express');
const router = express.Router();
const skate_tricks = require('../models/SkateTrick');
// @route GET api/skateboard_tricks
// @desc skateboard tricks data
// @access public
router.get('/', (req, res) => {
skate_tricks.find({}, (err, result) => {
if (err) {
res.send(err);
} else {
const trick_list = result[0];
res.send(trick_list);
}
});
});
module.exports = router;
Notice where res.send(trick_list)
no longer has .tricks
tied to it. Here is the code in the API call:
const [trickList, setTrickList] = useState([]);
const [loading, setLoading] = useState(false);
const sfsApiCall = axios.create({
baseURL: 'http://localhost:5000/',
});
const getTrickData = async () => {
try {
const data = await sfsApiCall.get('api/skateboard_tricks').then((res) => {
setTrickList(res.data.tricks);
});
setLoading(true);
} catch (err) {
console.error(err.message);
}
};
useEffect(() => {
getTrickData();
}, [loading]);
Note that I'm now referencing res.data.tricks
in setTrickList
. I spent 2 days on this stupid error so I hope this post can help someone else.
Thanks to everyone that chimed in. I feel like it all still helped to troubleshoot. This code was last worked on 8 months ago so it's likely one of the dependencies got updated to require this workaround when I updated all of my npm packages.