BackgroundI'm building a MERN full stack application as a personal project. I am running the frontend client on localhost:3000 and the server on localhost:5000.ProblemAll of my API routes work as expected except for a GET request, router.get('/get-friends', ...) which queries the mongoDB to return a list of collection documents. Calling that get request on Postman returns the expected output. I decided to write a simple GET request that returns a method and it works just fine in my browserWhen making the request the get-friends request in my browser, I get the following log:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/users/get-friends/. (Reason: CORS request did not succeed) What I've Already TriedEnabling cors in my Express serverEnabling cors preflightAdding a proxy to the server from the client's package.jsonSwitching from Axios to vanilla JS's fetch() methodTurning off cors in my browser (not ideal lol)I suspect the issue occurs when I make the request to the database from Express. I am really not sure how to solve this issue.Here is the route in question:router.get('/get-friends', (req, res) =>{ var species_ = req.body.species; var gender_ = req.body.gender; var neutered_ = req.body.neutered; // query db Friend.find({species: species_},{gender:gender_},{neutered:neutered_}).then((friends_) =>{ if(!friends_){ return res.status(404).send('query error, nothing returned'); } return res.send(friends_); }).catch((e) =>{ res.status(400).send(4); }) }); Here is the project repository and the relevant files are:https://github.com/edgarvi/foster-friends/server.js (Express server) https://github.com/EdgarVi/foster-friends/blob/master/routes/api/users.js (Routes for the express server) https://github.com/EdgarVi/foster-friends/blob/master/client/src/components/layout/SearchFriends.js (React component which calls the server) I would greatly appreciate any help!
Submitted October 07, 2019 at 08:49PM by BB_code4me
No comments:
Post a Comment