koa 返回图片视频文件、json、xml等数据

Node.js 2020-02-23 阅读 1208 评论 0

使用 koa2 中间层返回各种数据类型,主要是设置回应头content-type,比如JSON:application/json,XML:application/xml,png:image/png,jpg/jpeg:image/jpeg等等。数据类型的 mime type,可以使用 nodejs 的第三方工具 mime-types 来获取。对于一些流处理,可以使用fs.createReadStream()方法读取,但是如果 response 头不指定content-type,浏览器可能会当作下载处理。

示例源码

server.js

const Koa = require('koa');
const app = new Koa();
const mime = require('mime-types')
const fs = require('fs');

app.use(ctx => {
    if (ctx.request.url === '/file') {
        var path = "/Users/apple/Downloads/201228bli.bmp";
        var mimeType = mime.lookup(path);
        const src = fs.createReadStream(path);
        ctx.response.set("content-type", mimeType);
        ctx.body = src;
    } else if (ctx.request.url === '/json') {
        var jsonType = mime.lookup('json');
        ctx.response.set("content-type", jsonType);
        var json = {text: "Hello, World!"};
        ctx.body =  JSON.stringify(json);
    } else if (ctx.request.url === '/xml') {
        var jsonType = mime.lookup('xml');
        ctx.response.set("content-type", jsonType);
        var html = `
            <xml>
                <user>
                    <name>hello</name>
                </user>
            </xml>
        `;
        ctx.body = html;
    } else {
        ctx.body = "Hello World";
    }
});

app.listen(8000);

运行示例

运行示例的代码,执行命令行

$ node server.js

浏览器访问文件 http://localhost:8000/file

访问json http://localhost:8000/json

访问xml http://localhost:8000/xml

其他 url 的请求会返回字符串。

最后更新 2020-02-23