我遇到了 React 和 Node 的问题,无法调试。我的 Node 服务器上有一个到 coinmarketcap 的 API 连接,它返回硬币和单个硬币的列表。我在 postman 上得到了所有硬币端点和单个硬币端点返回的正确数据,但我只得到了所有硬币的 react ,而单个硬币返回 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" }));
我可以使用浏览器和 postman 毫无问题地访问/api/coin/btc 等端点。但是,当使用 React 时,我收到 404 错误: 获取http://localhost:3000/api/coin/BTC 404(未找到)
我是否遗漏了代理的某些内容,或者我是否弄乱了我的路线?感谢任何帮助,不确定缺少/没有看到什么。
最佳答案
我能够解决这个问题。这是代理的问题:
我必须包括:app.use(proxy("/api/**", { target: "http://localhost:5000 "})); 在我的代理定义中。
关于javascript - 无法通过代理从 React 和 Node 访问 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53347353/