【发布时间】:2019-04-09 00:01:07
【问题描述】:
通常我会使用 axios 发送一个 GET 请求,但是在“React 实践课程”教程中,讲师成功地点击了这条路线
app.get('/api/admin/download/:filename', auth, admin, (req, res) => {
console.log('here I am ', req.params.filename);
const file = path.resolve('.')+`/uploads/${req.params.filename}`;
res.download(file);
})
使用此代码中的链接
import {Link} from 'react-router-dom';
showFiles = () => (
this.state.files &&
this.state.files.map((filename,i) => (
<li key={i}>
<Link to={`/api/admin/download/${filename}`}
target="_blank">
{filename}
</Link>
</li>
))
)
正如here 所见,链接与服务器中的路径匹配,但反应路由器将我发送到 PageNotFound 组件,而不是发送 GET 请求。
为了让链接文件到达服务器,我缺少什么?我怀疑问题出在我的路由文件中。
const Routes = () => {
// null = public route
return (
<Layout>
<Switch>
<Route path="/admin/add_product" exact component={Auth(AddProduct, true)} />
<Route path="/admin/manage_categories" exact component={Auth(ManageCategories, true)} />
<Route path="/admin/manage_site" exact component={Auth(ManageSite, true)} />
<Route path="/admin/add_file" exact component={Auth(AddFile, true)} />
<Route path="/user/cart" exact component={Auth(Cart, true)} />
<Route path="/user/dashboard" exact component={Auth(Dashboard, true)} />
<Route path="/user/user_profile" exact component={Auth(UpdateProfile, true)} />
<Route path="/register_login" exact component={Auth(RegisterLogin, false)} />
<Route path="/register" exact component={Auth(Register, false)} />
<Route path="/product/:id" exact component={Auth(Product, null)} />
<Route path="/shop" exact component={Auth(Shop, null)} />
<Route path="/" exact component={Auth(Home, null)} />
<Route component={Auth(PageNotFound)} />
</Switch>
</Layout>
)
}
【问题讨论】:
-
您尝试过添加
<Route path="/api/admin/download/:filename" .....吗?现在您的路由器中没有任何与该 url 匹配的路由 -
那条路由不是意味着我想在前端处理路由,而不是将请求传递给服务器吗?
-
我误会了你。基本上,如果您不希望路由器控制您的链接,您可以在 Link 周围创建自己的包装器,或者只使用常规锚
-
谢谢。应该提到我已经尝试过 标签并得到了相同的行为。