typescript - 并非所有代码路径都在 Firebase 云函数中返回值
问题描述
我正在使用 TypeScript 编写云函数。我想调用另一个第三方 API。我已经创建了如下所示的函数。
export const postData= functions.https.onRequest((req, response) => {
if (req.method !== 'POST') {
return response.status(500).json({
message: 'not allowed'
});
}
else {
let phoneNumber = req.query.phoneNumber;
request('https://api.xyz.com/api/insertData.php?authkey=xxxxxx&userid=' + phoneNumber,
function (error: any, respon: any, body: any) {
console.log(body);
})
.then(function(xyz:any){
return response.status(200).json({
dataPosted: true
})
})
.catch(function(error:any){
return response.status(200).json({
dataPosted: false
})
})
}
});
但是当我尝试部署我的函数时,它会显示“并非所有代码路径都返回一个值”。但是我在if
&中都返回了响应else
。我究竟做错了什么?请帮忙
解决方案
您使用的请求库本机支持回调接口,但不返回承诺。
您可以使用request-promise
(https://github.com/request/request-promise)和rp()
“返回符合常规 Promises/A+ 的承诺”的方法,然后按如下方式调整您的代码:
//......
import * as rp from 'request-promise';
export const postData = functions.https.onRequest((req, response) => {
if (req.method !== 'POST') {
return response.status(500).send('not allowed');
} else {
let phoneNumber = req.query.phoneNumber;
var options = {
url:
'https://api.xyz.com/api/insertData.php?authkey=xxxxxx&userid=' +
phoneNumber,
method: 'POST'
};
return rp(options)
.then(function(parsedBody: any) {
response.send('data posted');
})
.catch(function(error: any) {
console.log(error);
response.status(500).send(error);
});
}
});
推荐阅读
- pyspark - Pyspark - 如何创建从单元格中复制特定数字的列
- javascript - 如何在 Javascript/Apps 脚本中组装 APRS 数据包?
- json - Symfony SerializerInterface 将 json 反序列化为类不起作用
- c# - 通过c#代码获取microsoft graph中的syncJobs返回未知错误
- c# - SQL 按多列对数据进行排序
- performance - RxJava 与 RxGo 的性能差异
- cocos2d-js - 如何收听鼠标按钮按住
- python - Python矩阵中的乘法
- javascript - 查询对象时 JSON Fetch 返回 undefined
- github - 如何共享/扩展/重用/参考 GitHub Workflow?