【发布时间】:2019-04-20 04:51:48
【问题描述】:
我无法调试 React 和 Node 的问题。我在我的节点服务器上有一个到 coinmarketcap 的 API 连接,它返回一个硬币和单个硬币的列表。我在邮递员上为所有硬币端点和单个硬币端点返回了正确的数据,但我只得到所有硬币的反应,而单个硬币返回 404 错误。Link to screenshot for API return of single coin on postman
这是我返回单个硬币的服务器端代码:
module.exports = app => {
app.get("/api/coin/:id", async(req, res) => {
const symbolID = req.params.id;
const requestOptions = {
method: "GET",
uri: "https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/info",
qs: {
symbol: symbolID.toUpperCase()
},
headers: {
"X-CMC_PRO_API_KEY": keys.testCoinAPI
},
json: true,
gzip: true
};
try {
await rp(requestOptions).then(response => {
res.send(response.data);
});
} catch (err) {
res.send("Sorry the currency you are looking for is not available");
console.log(err);
}
});
};
这是我使用 API 的 React 代码
import React, {
Component
} from "react";
import axios from "axios";
class ViewCoin extends Component {
componentDidMount() {
const {
match: {
params
}
} = this.props;
axios.get(`/api/coin/${params.symbol}`).then(({
data: coin
}) => {
console.log(coin);
this.setState({
coin
});
});
}
render() {
return <h1 > This is the view coin component < /h1>;
}
}
export default ViewCoin;
这是我的 renderCoins 函数,用于将数据放入表中。带有个人链接。
renderCoins() {
return this.props.coins.map(coin => {
return (
<tr key={coin.id}>
<td>
<Link to={`/coin/view/${coin.symbol}`}>{coin.name}</Link>
</td>
<td>{coin.symbol}</td>
<td>${coin.quote.USD.price}</td>
<td>${coin.quote.USD.market_cap}</td>
<td>{coin.circulating_supply}</td>
<td>${coin.quote.USD.volume_24h}</td>
<td>{coin.quote.USD.percent_change_24h}%</td>
</tr>
);
});
}
我也在使用代理来路由后端和前端端口:
app.use(proxy("/api/*", { target: "http://localhost:5000" }));
我可以使用浏览器和邮递员毫无问题地访问 /api/coin/btc 等端点。但是,在使用 React 时出现 404 错误: GET http://localhost:3000/api/coin/BTC 404(未找到)
我是否遗漏了代理的某些内容,或者我是否弄乱了我的路线?任何帮助表示赞赏,不确定缺少/没有看到什么。
【问题讨论】:
-
您的目标是
"http://localhost:5000"使用端口5000,但是您指出的错误是尝试使用3000,http://localhost:3000/api/coin/BTC这只是写问题时的错误吗? -
localhost:5000 指向服务器的端口。 localhost:3000 是反应应用程序。代理允许您从前端的localhost:3000 访问 5000 端口上的路由。这不是一个错字,它是这样设计的,它适用于我在应用程序中的所有其他 API。这个特定的错误有点令人困惑。
标签: javascript node.js reactjs blockchain cryptocurrency