使用Express作为代理服务器,React.js返回404



我正试图从express向第三方api发出请求,我希望express作为代理,并将结果发送到前端。问题是前端的路由有查询和参数,这是我的代码

app.get("/api/posts/:id", function (req, res) {
request(
"https://api.xxxx.com/yyyy/1897970/user",
{
headers: {
Authorization: API_KEY,
"Content-Type": "application/json",
},
},
function (error, response, body) {
const per_page = req.query.per_page;
const page = req.query.page;
const query = req.query.query;
const id=req.params.id;
if (!response.body) {
console.log(error);
} else {
res.send({
body,
id,
"per-page": per_page,
page: page,
query: query
});
}
}
);
});

在前端,我必须向像

这样的路由发出请求
axios
.get(
`/api/posts/{id}/query?per_page=10&page=${title}`)
.then((res) => { 

}).catch((err)=>{console.log (err) })

问题是,它返回一个错误404,它不能得到数据,请我做错了什么?

get中的URL不是完整的URL。如果你是在localhost,那么把它改成你的后端完整的URL。

将代理添加到包中。Json从后端获取数据

"proxy": "http://localhost:3000",

代理应该是后端运行的端口。

最新更新