2021-12-01

Node Express API -- Dynamic Routing with React

I am trying to create a Node Express API and host it on Heroku. I'm using React on the front end to display the data.

I have no problem displaying the data in a list, but I need dynamic routing, so when the user clicks on one of the products, they're redirected to a new page with additional information. With my current code, I get an 'Internal Server Error' and a 404 on the front end

https://shoppingapiacme.herokuapp.com/shopping/ This is a random API that I found, but a good example of what I'm trying to accomplish. If you put an id at the end of this URL, you are redirected to that just that product's information.

Here's a link to mine: http://tentapinodejs.herokuapp.com/tents/

I have very little experience with Node/Express, so any help would be greatly appreciated!

EDIT: Here's a codeSandbox of the React with the other Shopping API that I want to emulate. If I try to fetch the data from my API, codesandbox gives a network error. I don't get this network error when using the link in VScode

https://codesandbox.io/embed/cocky-snow-1oi8m?fontsize=14&hidenavigation=1&theme=dark

const express = require('express');
const cors = require('cors')
const app = express();

app.use(cors())

const importData = require("./data.json"); 

let port = process.env.PORT || 3000;

app.get('/', (req, res) => {
    res.send("Hello world")
})

app.get('/tents', (req, res)=> {
    res.send(importData);
})

app.get('/tents/:id', function(req , res){
  res.render('tents/' + req.params.id);
});


app.listen(port, ()=> {
    console.log(`example app is listening on http://localhost:${port}`);
})


from Recent Questions - Stack Overflow https://ift.tt/32GJ6jX
https://ift.tt/eA8V8J

No comments:

Post a Comment