這里示例用post的方式發(fā)送數(shù)據(jù),并在云函數(shù)獲取數(shù)據(jù)
寫(xiě)了個(gè)helloword,代碼如下:
exports.main = async (event, context) => {
console.log(event)
const obj = JSON.parse(event.body)
return {
result: 0,
resInfo: 'Hello ' + obj.name
}
};
這樣我們就可以通過(guò)postman發(fā)送post請(qǐng)求訪問(wèn),我是直接用python訪問(wèn),代碼如下:
#post請(qǐng)求提交用戶信息到服務(wù)器
import urllib.request
import urllib.parse
import ssl
import json
context = ssl._create_unverified_context()
url = 'https://cloudbasedemo-9go8tl9mf682c3c7-1301583309.ap-guangzhou.app.tcloudbase.com/say-hello'
values = {
'name' : 'elikong',
'location' : 'shenzhen',
'language' : 'Python' }
data = json.dumps(values).encode('utf-8')
print(data)
req = urllib.request.Request(url, data=data)
with urllib.request.urlopen(req, context=context) as response:
html = response.read()
print(html.decode("utf-8"))
print(response.code)
在使用過(guò)程中由于開(kāi)始錯(cuò)誤的訪問(wèn)了body數(shù)據(jù),把代碼寫(xiě)成了:
JSON.parse(event[body])
導(dǎo)致json解析總是錯(cuò)誤,后來(lái)發(fā)現(xiàn)只能寫(xiě)成
JSON.parse(event.body)
或者
JSON.parse(event['body'])
如果想使用云控制臺(tái)上的測(cè)試模板-hello world事件模板,就需要改代碼為下面的形式,就比較統(tǒng)一了
exports.main = async (event, context) => {
console.log(event)
let obj = null
if(event.body != null){
obj = JSON.parse(event['body'])
} else {
obj = event
}
return {
result: 0,
resInfo: 'Hello ' + obj.name
}
};
測(cè)試模板用:
{
"name": "elikong"
}