나는 Node.js
에 노력하고 다음 코드를 사용하여 몇 가지 문제가, 문제가 해결 발생,하지만 난 알고 싶어했습니다 이유 : (_
이 lodash
입니다 request
는 NPM의 request
^2.60.0
패키지)다음 두 코드 블록의 차이점은 무엇입니까?
var send = (options, type) =>
(req, res, next) => {
var defaultOptions = {
baseUrl: config.urlprefix,
method: 'GET',
encoding: 'utf8',
header: {
'Content-Type': 'application/json'
}
}
options = options || {};
if (_.isFunction(options)) {
options = _.assign(defaultOptions, options(req));
}
else if (_.isObject(options)) {
options = _.assign(defaultOptions, options);
}
request(options, parseResToJSONAndSend(res, type));
};
이 잘 작동하지 않습니다 내가 send
전화를 두 번째 (더 많은) 시간, request
의 options
매개 변수 내가 PARAMS이 send
에 전달 변경된 경우에도 그냥 send
전화를 처음과 동일하고, 그 이후로 절대로 바뀌지 않을거야. 티.
var send = (options, type) =>
(req, res, next) => {
var defaultOptions = {
baseUrl: config.urlprefix,
method: 'GET',
encoding: 'utf8',
header: {
'Content-Type': 'application/json'
}
}
var opt = options || {};
if (_.isFunction(options)) {
opt = _.assign(defaultOptions, opt(req));
}
else if (_.isObject(options)) {
opt = _.assign(defaultOptions, opt);
}
request(opt, parseResToJSONAndSend(res, type));
};
이 시간은 잘 작동합니다. 그러나 나는 문제가 어디 있는지 알지 못한다. 누군가 나를 도와 줄 수 있습니까? 감사!
것은 명확하게하기 : stock
컨트롤러의 수비력을 :
var apis = {
stocks: (req) => ({
url: SOME_URL
}),
...
};
var mod = {};
Object.keys(apis).map((key) => {
mod[key] = request(apis[key]);
});
module.exports = mod;
stock
컨트롤러의 사용 :
router.get('/some-path',stock.stocks);
데프 parseResToJSONAndSend
의 :
var parseResToJSONAndSend = (res, type) =>
(err, resp, data) => {
if (err) {
console.log("Response err", err);
} else if (resp.statusCode < 200 || resp.statusCode > 299) {
console.log("Status code not in range 200..299:", resp.statusCode, resp.request.uri.href);
} else {
console.log(resp.request.uri.href, resp.statusCode);
try {
if (type == 'json') {
res.json(JSON.parse(data));
}
else {
res.send(data);
}
} catch (e) {
console.log("Err in JSON parse", e);
}
}
};
네, 두 번째는 내가이 ES6 바로 가기 구문의 일부를 싫어하는 곳은 다른 옵션 – cmal
를 전달합니다. 이것을 ES5 구문으로 작성했다면, 어떤 일이 일어나고 있는지 더 분명하게 알 수있을 것입니다. – jfriend00
감사합니다. 이런 일이 일어나는 명백한 이유가 없다는 것을 의미합니까? – cmal