我是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\": message\n }]\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();
};
答案 0 :(得分:2)
您可以轻松地检索Within the Context
对象,因为函数result
返回了解决该对象的Promise,因此应该可以:
request1
此外,request1().then((resultObject)=>{
//resultObject === result
return res.send(resultObject);
});
返回一个承诺,所以您应该这样做:
res.json()