【发布时间】:2022-01-07 11:07:19
【问题描述】:
我正在尝试创建一个 Node Express API 并将其托管在 Heroku 上。我在前端使用 React 来显示数据。
我在列表中显示数据没有问题,但我需要动态路由,因此当用户点击其中一个产品时,他们会被重定向到包含附加信息的新页面。使用我当前的代码,我在前端收到“内部服务器错误”和 404
https://shoppingapiacme.herokuapp.com/shopping/ 这是我发现的一个随机 API,但它是我想要完成的一个很好的例子。如果您在此 URL 的末尾添加一个 id,您将被重定向到该产品的信息。
这是我的链接:http://tentapinodejs.herokuapp.com/tents/
我在 Node/Express 方面的经验很少,因此非常感谢任何帮助!
编辑:这是 React 的代码沙盒以及我想要模拟的其他购物 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 数据显示为minimal reproducible example。显然,您的某些链接已损坏,但我看到的只是 JSON 转储和非链接,因此这里似乎缺少一些上下文信息,例如 HTML。谢谢。
标签: javascript node.js api express routes