node.js koa 怎么在后端使用koa-router koa-send定义一个供前端下载文件的接口
时间: 2024-06-11 15:04:13 浏览: 211
首先,需要安装koa、koa-router和koa-send模块:
```
npm install koa koa-router koa-send
```
然后,在后端代码中引入这三个模块:
```javascript
const Koa = require('koa');
const Router = require('koa-router');
const send = require('koa-send');
```
接着,创建一个Koa实例和一个Router实例:
```javascript
const app = new Koa();
const router = new Router();
```
定义一个供前端下载文件的接口,这里假设文件名为test.txt,存放在项目根目录下的public目录中:
```javascript
router.get('/download', async (ctx) => {
const filePath = `${__dirname}/public/test.txt`;
await send(ctx, filePath);
});
```
最后,将Router实例应用到Koa实例上,并启动服务:
```javascript
app.use(router.routes());
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
```
这样,前端就可以通过访问http://localhost:3000/download来下载test.txt文件了。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)