0

Hi I've written the following route for an api endpoint which isn't working. When I test with Postman and my code, it's simply a 404 not found error.

router.patch("/favorite", async (req, res) => {
  user = await User.findById(req.body.id)
  if (user == null) {
    return res.status(404).json({ message: 'Cannot find user' })
  }
  if (req.body.putArr != null) {
    res.user.favPokemon = req.body.putArr;
  }
  try {
    const updatedUser = await res.user.save();
    console.log(res.user.favPokemon);
    console.log(updateUser);
    res.json(updatedUser);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

What am I missing/what error do I have in my code? For reference, here's my mongoDB setup for users: enter image description here

Edit: Apologies for not specifying the endpoint. To be more clear, the end point and code calling this is:

const favThis = async (e) => { // Patch method to favorite or unfavorite a pokemon
    debugger;
    e.preventDefault();
    try {
      console.log(putArr);
      const newUser = {userID, putArr};
      await axios.patch("http://localhost:5000/users/favorite", newUser);
    } catch(err) {
      err.response.data.msg && setError(err.response.data.msg)
    }
    };

, so it's http://localhost:5000/users/favorite. I have other endpoints working fine such as http://localhost:5000/users/login and http://localhost:5000/users/register, and inside server.js I have app.use("/users", require("./routes/users"));

Additionally, server.js is simply

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv").config();

// set up express

const app = express();
app.use(express.json());
app.use(cors());

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`The server has started on port: ${PORT}`));

// set up mongoose
mongoose.connect(
  process.env.MONGODB_CONNECTION_STRING,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  },
  (err) => {
    if (err) throw err;
    console.log("MongoDB connection established");
  }
);

// set up routes

app.use("/users", require("./routes/users"));
app.use("/todos", require("./routes/todo"));

Edit 2:: I notice now that when I test on Postman, it's an infinite loop and the call is hung. I also get the following warnings in my console:

(node:36447) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

and

(node:36447) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

matthewcy
  • 41
  • 8
  • 2
    What does your HTTP request look like? – Lin Du Jun 03 '21 at 03:27
  • 1
    What is the base url for your API? This should defined in your `index.js` or whatever entry point you are using. It should be something like `https://localhost:3000/api/favorite` – Jeremy Hamm Jun 03 '21 at 04:09
  • I noticed the port is different in your post vs comment (3000 v 5000). Is `router.patch` included in `server.js`? – Jeremy Hamm Jun 03 '21 at 04:53
  • Sorry I made another mistake, I meant to write localhost:5000/users/favorite in the comment. And no, I have router.patch along with my other HTTP methods/routes in users.js, under a routes folder. Server.js simply has `app.listen`, the port, and connects with mongoDB – matthewcy Jun 03 '21 at 04:58
  • When you hit the endpoint is this the 404 you are seeing? `return res.status(404).json({ message: 'Cannot find user' }) }`. Based on what you've posted the code looks correct. – Jeremy Hamm Jun 03 '21 at 05:07
  • Hm I may have made some change earlier, but the code above is what I just used to test on Postman and the call is hung and runs infinitely. In my console it also gives some warnings that I'll put in an edit – matthewcy Jun 03 '21 at 05:16
  • Also I generally find `if (!user)` superior to `if (user == null)` and `if (req.body.putArr != null)` is the same as `if (req.body.putArr)` – Jeremy Hamm Jun 03 '21 at 05:18
  • I see, yeah I made those edits and unfortunately I'm having the same issues. Maybe it's just something simple that we're overlooking – matthewcy Jun 03 '21 at 05:23

1 Answers1

0

Based on the warning you have failing code inside a promise which is not being caught. Perhaps in this line user = await User.findById(req.body.id).

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

Jeremy Hamm
  • 499
  • 1
  • 5
  • 14
  • Thank you, all I did was place everything inside of the 'try' braces. However, now I have the error 'cannot set property of 'favPokemon' of undefined', so I'll work through that now! – matthewcy Jun 03 '21 at 06:00