Checking out a mongodb record by object identification

I've been building an inventory system using the MERN stack. However, when I attempt to view products with the code below, it always returns 'No Matching Product' even though there are matching products in my collection. The backend works fine when tested with Postman. What could be causing this issue and how can I resolve it?

const ViewProduct = () => {
  const {prodID} = useParams()
  const [product, setProduct] = useState(null);
  const [isCalling, setIsCalling] = useState(false);
 

  useEffect(() => {
    const getProduct = async () => {
      setIsCalling(true);

      await axios.get('https://localhost:4000/api/products/',{params:prodID}
      ).then(response => {
        setProduct(response.data)
      }).catch(error => {
        console.error(error);
      })

      setIsCalling(false);
    };

    getProduct();
  }, [prodID]);

  if (isCalling) {
    return <div>Loading...</div>;
  }

  if (!product) {
    return <div>No matching products</div>;
  }

  return (
    <><div>
      <h2>{product.name}</h2>
      <p>Product ID: {prodID}</p>
      <p>Description: {product.descr.join(', ')}</p>
      <p>Type: {product.type}</p>
      <p>Sub-type: {product.sub_type}</p>
      <p>No of Stock Remaining: {product.noOfStockRemaining}</p>
      <p>Archived: {product.archived ? 'Yes' : 'No'}</p>
      <p>Archived On: {product.archived_on}</p>
      <Button>Delete</Button>
      <Button >Add Stock</Button>
      <Button>Back To Inventory</Button>

    </div>
    </>

  );
};

backend:

const getAProduct = async (req, res) => {
    const { id } = req.params
    //revisit ths validation after importing nanoid
    if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.json({ error: 'no matching products' })
    }
    const product = await Product.findById(id)

    if (!product) {
        return res.json({ error: 'no matching products' })
    }

    res.json(product)
}

In addition, I have created a middleware that runs every time a request is sent so I can monitor the requests. When testing the backend with Postman, it shows that I'm sending a GET request, but nothing happens when trying to do it from the frontend.

 app.use((req, res, next) =>{
    console.log(req.path, req.method)
    next()
})

Update: A certain error appears in the console

Cross-Origin Request Blocked: The Same Origin Policy prevents reading the remote resource at https://localhost:4000/api/products/. (Reason: CORS request did not succeed). Status code: (null)

I have already installed and configured CORS successfully, and it works for other requests. I also tried adding withCredentials:true to the axios parameters, but it still didn't work.

EDIT: There was a typo in the axios URL - I had typed 'https' instead of 'http' for localhost. Thank you everyone for your assistance.

Answer №1

To successfully pass the parameter, use the following code:

await axios.get(`https://example.com/api/items/${itemId}`);

Make sure to declare the route like this:

app.get('/api/items/:id', fetchItem)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are you experiencing issues with the cross-origin request failing in react-map-gl?

While setting up a map in react-map-gl and providing my access token, I encountered the following console error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://events.mapbox.com/events/v2?access_token= ...

React Native encountered an error: `undefined` is not an object

Encountering the commonly known error message "undefined is not an object" when attempting to call this.refs in the navigationOptions context. Let me clarify with some code: static navigationOptions = ({ navigation, screenProps }) => ({ heade ...

Install all dependencies again by running `npm install -g download`

My package.json file includes a list of 10 dependencies. Whenever I run npm install -g, all the dependencies get downloaded again, causing delays due to the lengthy process. I am wondering if there is a way to utilize the existing dependencies stored in ...

Having trouble passing a React Router Link component into the MuiLink within the theme

The MUI documentation explains that in order to utilize MuiLink as a component while also utilizing the routing capabilities of React Router, you need to include it as a Global theme link within your theme. An example is provided: import * as React from & ...

Am I using Node.js, Express, and Promises correctly in my code?

In my Express route, I initially encountered an issue where input data passed through 3 different functions was being queued and returned one at a time. After some testing, I discovered this bottleneck and decided to refactor my code. I modified the functi ...

What is the best method for implementing pagination in Larvael with React using Inertia?

Is there a way to paginate in react using inertia with laravel? When pulling paginated data, I use the following code: $contacts = Contact::orderBy('name', 'asc')->paginate(10); return Inertia::render('Contacts/index', [ ...

Creating a custom regular expression in ExpressJS: matching a parameter to all routes except for one

My current route is set up to catch the code param in the following way: app.get('/:code([a-zA-Z]{3})', codeHandler); This setup successfully matches all three-letter codes, but now I want to modify it to exclude one specific code. For example, ...

Building a Full-Stack Application with React, Express, and Passport

I'm in the process of setting up a full-stack application that utilizes React and Express JS. For authentication, I have implemented Passport.js but encountered a minor issue... My front-end and back-end are running as separate packages on different ...

The response from a post request in Reactjs using axios is coming back empty

When working on my Reactjs app, I am using axios.post() to edit a mysql database on the backend. The data is successfully sent through the post request to the backend. However, I am facing an issue where I need to determine when the post request has finish ...

Error: Order placement failed due to a validation error

I've been working on developing an ecommerce application, and while the frontend is complete, I've encountered a problem when placing an order. After going through all my files, I couldn't pinpoint where the issue was originating from. Despi ...

Dealing with empty search results in material-table while utilizing React and remote data

I am currently utilizing the material-table library with React to handle remote data. When no search results are found, I am attempting to figure out how to hide the spinner and display a message stating "No records to display". The search function trigger ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

Having trouble setting a defaultProps using createTheme in MUI v5?

Just dipping my toes into Material-UI v5, and I'm eager to craft a custom theme using createTheme for styling a button component. As per the guidance shared in the documentation: The key components within the theme enables direct customization of a ...

Issue: "Exported functions in a 'use server' file must be async"

I'm currently working on implementing layout.tsx in the app directory of Next.js 13 to create a navigation layout that appears on all pages. I've successfully configured it so that the navbar updates when a user logs out or signs in, but there&ap ...

Using Express to request data from Mongo database and only receiving the path

I've been troubleshooting a websocket function that interacts with MongoDB to fetch some data stored in the system using 'get'. const User = require('mongoose'); const express = require('express'); const cal = require(&a ...

The state update is triggering a soft refresh of the page within Next.js

In my Next.js project, I have integrated a modal component using Radix UI that includes two-way bound inputs with state management. The issue arises when any state is updated, triggering a page-wide re-render and refreshing all states. Here is a snippet of ...

Discovering the most recent update date of Node packages

I recently noticed that one of the node dependencies my project relies on has been updated since a few days ago. The update caused my test suite to fail, even though I haven't made any changes to my code or package.json in that time. It seems like NPM ...

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...

Encountering issues with retrieving application setting variables from Azure App Service in a ReactJS TypeScript application resulting in '

My dilemma lies in my app setup which involves a Node.js runtime stack serving a ReactJs Typescript application. I have set some API URLs in the application settings, and attempted to access them in ReactJs components using process.env.REACT_APP_URL, only ...

The process of combining multiple JS files into one with Gulp 4 has encountered an issue: an error has occurred stating

I am currently utilizing Nodejs version 12.9.0 along with gulp version 4.0.2 My objective is to concatenate and minify multiple JS files from various source directories and bundle them into a single JS file. After concatenation and minification, I encount ...