繁体   English   中英

Node Express API -- 使用 React 的动态路由

[英]Node Express API -- Dynamic Routing with React

我正在尝试创建一个 Node Express API 并将其托管在 Heroku 上。 我在前端使用 React 来显示数据。

我在列表中显示数据没有问题,但我需要动态路由,因此当用户单击其中一个产品时,他们会被重定向到包含附加信息的新页面。 使用我当前的代码,我在前端收到“内部服务器错误”和 404

https://shoppingapiacme.herokuapp.com/shopping/这是我发现的随机 API,但这是我想要完成的一个很好的例子。 如果您在此 URL 的末尾添加一个 id,您将被重定向到该产品的信息。

这是我的链接: http://tentapinodejs.herokuapp.com/tents/

我对 Node/Express 的经验很少,所以任何帮助都将不胜感激!

编辑:这是 React 的 codeSandbox 以及我想要模拟的其他 Shopping API。 如果我尝试从我的 API 中获取数据,codesandbox 会出现网络错误。 在 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}`); })

所以我认为你想要一个产品的 JSON 数据,基于 ID,就像你的例子一样?

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

在这里,您尝试渲染名称为“tents/”的视图(可能存在也可能不存在,并且很可能不会给出错误),并由 ID 连接,因此例如一些名为“tents/1”的视图.

而您想要做的(为了达到与您的示例相同的结果)类似于以下内容:

app.get('/tents/:id', function(req , res){
  const result = importData.filter(data => {return data.id == req.params.id})
  res.send(result);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM