我完全是Javascript的新手,正试图在我使用的两个服务之间架起一座桥梁。目标只是获取主体或请求,对另一个服务进行promise api调用,以使用该api调用的主体进行响应。我已经能够获取请求的主体并将其发送到服务,但我在接收该响应并将该响应的主体作为函数的响应时遇到了问题。请帮帮我。非常感谢。
var moment = require('moment');
var CryptoJS = require("crypto-js");
const fetch = require('node-fetch');
var unixtime = moment().unix();
var apiUser = process.env.apiUser;
var secret = process.env.apiKey;
var url = process.env.url;
exports.test = (req, res) => {
var message = req.body;
message = JSON.stringify(message);
var body = "{n "ops": [{n "conv_id": "679690",n "type": "create",n "obj": "task",n "data": messagen }]n}n"
body = body.replace(/message/ig, message);
var signature = CryptoJS.enc.Hex.stringify(CryptoJS.SHA1(unixtime + secret + body + secret));
function request1() {
return new Promise((resolve, reject) => {
var options = fetch(url+apiUser+'/'+unixtime+'/'+signature, {
method: 'post',
body: body,
headers: { 'Content-Type': 'application/json' },
});
options.then(res => {
var result = res.json;
console.log(result);
resolve(result);
})
.catch(() => { // if .then fails
console.log('Promise rejected');
let rejectMessage = 'Sorry, an error occurred.';
reject(rejectMessage); // Promise rejected
});
});
}
request1();
};
您可以很容易地检索result
对象,因为函数request1
返回一个解析该对象的promise,所以这应该有效:
request1().then((resultObject)=>{
//resultObject === result
return res.send(resultObject);
});
此外,res.json()
返回一个promise,因此您应该执行以下操作:
options.then(res => res.json()).then(result => {
console.log(result);
resolve(result);
})