我正在使用rest.js
中的npm install rest
,并且无法将我的参数附加到请求中的路径。这是我的client.js
'use strict';
var rest = require('rest');
var defaultRequest = require('rest/interceptor/defaultRequest');
var mime = require('rest/interceptor/mime');
var uriTemplateInterceptor = require('rest/interceptor/template');
var errorCode = require('rest/interceptor/errorCode');
var baseRegistry = require('rest/mime/registry');
var registry = baseRegistry.child();
registry.register('text/uri-list', require('./api/uriListConverter'));
registry.register('application/hal+json', require('rest/mime/type/application/hal'));
module.exports = rest
.wrap(mime, { registry: registry })
.wrap(uriTemplateInterceptor)
.wrap(errorCode)
.wrap(defaultRequest, { headers: { 'Accept': 'application/hal+json' }});
我使用了https://github.com/cujojs/rest/blob/master/docs/interceptors.md#module-rest/interceptor/template建议的模板拦截器。这是我的代码发出请求:
client({method: 'GET', path: 'api/questions/page', params: {offset: 0, limit:10}})
.then(response => console.log(response.request.path));
console.log(response.request.path)
的输出是api / questions / page,它也不显示网络日志中的请求参数。如何让params附加到路径上?
答案 0 :(得分:0)
我刚创建了自己的拦截器
define(function(require) {
'use strict';
var interceptor = require('rest/interceptor');
return interceptor({
request: function (request /*, config, meta */) {
/* If the URI is a URI Template per RFC 6570 (http://tools.ietf.org/html/rfc6570), trim out the template part */
if (request.path.indexOf('{') === -1) {
if(request.params != null){
request.path = request.path + '?'
Object.keys(request.params).forEach(function eachKey(key){
request.path = request.path + key + '=' + request.params[key] + '&';
});
request.path = request.path.slice(0, -1);
}
return request;
} else {
request.path = request.path.split('{')[0];
return request;
}
}
});
});