Express / Node Repsonse Headers丢失了?

时间:2017-02-18 12:47:05

标签: node.js angular express

我已经构建了一个Express / NodeJS REST API,它在响应上设置了一个Header:

router.route("/api/articles")
    .get(authCheck, function (req, res) {
        let pagination = req.get('Pagination').split(",");
        let currentPage = pagination[0];
        let currentPageSize = pagination[1];
        let skip = (currentPage - 1) * currentPageSize;
        var response = {};
        articlesOp.count({}, function (err, totalItems) {
            articlesOp.find({}, function (err, data) { response = data; }, {
                sort: {
                    artNr: 1
                }
            }).skip(skip > 0 ? ((currentPage - 1) * currentPageSize) : 0).limit(currentPageSize).exec(function (err, docs) {
                if (err)
                    res.json(err);
                else {
                    res.setHeader('Pagination', '{"page": ' + currentPage + ', "pageSize": ' + currentPageSize + ', "totalItems": ' + totalItems + ', "totalPages": ' + Math.ceil(totalItems / currentPageSize) + '}');
                    res.setHeader('X-Foo', 'bar');
                    res.json(response);
                }
            });
        });

    });

在Postman中执行thsi API时,我可以看到Headers Section中设置了floowing标头:

Access-Control-Allow-Origin →*
Connection →keep-alive
Content-Length →3697
Content-Type →application/json; charset=utf-8
Date →Sat, 18 Feb 2017 10:05:10 GMT
ETag →W/"e71-NQjTx6uFpe8cuvaoLUXPOg"
Pagination →{"page": 3, "pageSize": 10, "totalItems": 442, "totalPages": 45}
X-Foo →bar
X-Powered-By →Express

但是当我从Angular2应用程序执行代码时,标题除了" Content-Type"不存在。 (或者至少我找不到它们)

let headers = new Headers();
if (page != null && itemsPerPage != null) {
            headers.append('Pagination', page + ',' + itemsPerPage);
        }

        return this.authHttp.get(this._baseUrl + 'articles', {
            headers: headers
        })
            .map((res: Response) => {

                console.log(res.headers.keys());
                pResult.result = res.json();

                if (res.headers.get("Pagination") != null) {
                    //var pagination = JSON.parse(res.headers.get("Pagination"));
                    var paginationHeader: Pagination = this.itemsService.getSerialized<Pagination>(JSON.parse(res.headers.get("Pagination")));
                    console.log(paginationHeader);
                    pResult.pagination = paginationHeader;
                }
                return pResult;
            })
            .catch(this.handleError);

1 个答案:

答案 0 :(得分:1)

添加CORS异常可以解决问题:

res.setHeader("access-control-expose-headers", "Pagination");