通常我会使用axios发送一个GET请求,但是在“反应实践课程”教程中,讲师成功地找到了这条路线
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所示,该链接与服务器中的路径匹配,但是React Router却将我发送给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>
)
}
答案 0 :(得分:1)
要扩大我的评论,我在这里回答。
以下对我有用:
import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const About = () => <div>About</div>
const Home = () => <div>Home</div>
const Topics = () => <div>Topics</div>
const apiUrl = "http://localhost:9000/api";
const BasicExample = () => (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
<li>
<a href={`${apiUrl}/v1/test`}>Api GET request</a>
</li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</div>
</Router>
);
render(<BasicExample />, document.getElementById("root"));
因此,基本上我只是创建了一个<a>
并传递了正确的href
网址,但并未落入<Router>
中,如此处所示:https://github.com/ReactTraining/react-router/issues/1147#issuecomment-113180174
确定要传递正确的URL到锚的href吗?