javascript – 如何处理/解析/读取“multipart / mixed; boundary = batch“响应

如何使用 JavaScript / jQuery处理/解析/读取“multipart / mixed; boundary = batch”类型的响应?

在我们的应用程序中,我们得到如下响应:

有办法处理这类回复吗?或者我们应该使用正则表达式等原始字符串操作来获取我们想要的内容

--batchresponse_e3e3tc10-1181-4b94-bb8a-952452769d53
Content-Type: multipart/mixed; boundary=changesetresponse_4sdflwerf-40ef-4347-8c77-b364e5d2e678

--changesetresponse_4sdflwerf-40ef-4347-8c77-b364e5d2e678
Content-Type: application/http
Content-transfer-encoding: binary

HTTP/1.1 201 Created
DataServiceVersion: 1.0;
Content-Type: application/json;odata=verbose;charset=utf-8
Content-ID: 1
X-Content-Type-Options: nosniff
Cache-Control: no-cache
Location: <url1>

{"Some": "JSON response"}
--changesetresponse_4sdflwerf-40ef-4347-8c77-b364e5d2e678
Content-Type: application/http
Content-transfer-encoding: binary

HTTP/1.1 204 No Content
Content-ID: 2
X-Content-Type-Options: nosniff
Cache-Control: no-cache
DataServiceVersion: 1.0;


--changesetresponse_4sdflwerf-40ef-4347-8c77-b364e5d2e678
Content-Type: application/http
Content-transfer-encoding: binary

HTTP/1.1 204 No Content
Content-ID: 3
X-Content-Type-Options: nosniff
Cache-Control: no-cache
DataServiceVersion: 1.0;


--changesetresponse_4sdflwerf-40ef-4347-8c77-b364e5d2e678--
--batchresponse_e3e3tc10-1181-4b94-bb8a-952452769d53--

解决方法

不幸的是,似乎没有一个库来处理这个问题.这就是我最终做的事情.以下解决方案假定角度和lodash(“_”)可用,但它可以适应其他框架.

鉴于responseCollection是初始帖子中显示的http响应,我们首先从初始头部找到边界.然后,使用该边界将响应拆分为其组件.在每个组件中,假设第一个“{”标记JSON的开头,“}”的最后一个实例标记为结尾. JSON被反序列化并推送到响应对象的集合.

这显然不适用于每个场景并做出一些广泛的假设,但这足以解决我的问题.

function parseBatch(responseCollection) {
        var items = [];

        var boundary = getBatchSeparator(responseCollection);

        var responseLines = responseCollection.data.split('--' + boundary);

        _.forEach(responseLines,function (response) {
            var startJson = response.indexOf('{');
            var endJson = response.lastIndexOf('}');

            if (startJson < 0 || endJson < 0) {
                return;
            }

            var responseJson = response.substr(startJson,(endJson - startJson) + 1);

            var item = angular.fromJson(responseJson);

            items.push(item);
        });

        return items;
    }

    function getBatchSeparator(response) {
        var headers = response.headers();

        if (!headers['content-type'])
            return ''; //would probably be bad if this happens,but not sure it ever will.

        var components = headers['content-type'].split(';');

        var boundary = _.find(components,function (o) { return _.startsWith(_.trim(o),'boundary=') });

        boundary = _.replace(boundary,'boundary=','');

        boundary = _.trim(boundary,'; ');

        return boundary;
    }

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...