English
Cloud function/cloud object URLization is an HTTP access service provided by uniCloud for developers, allowing developers to access cloud functions or cloud objects through HTTP URLs.
The following points need to be paid attention to after urlization
The cloud function supports URLization since its launch. URLization of cloud objects requires HBuilderX 3.5.2+. Hereinafter, unless cloud objects are specifically mentioned, cloud functions generally refer to common cloud functions and cloud objects.
This document mainly guides you how to manage and use cloud function URLization in the uniCloud web console.
Usage Restrictions
If the path of a cloud function is configured as /test
, the actual access to /test
, /test/a
, /test/b
will execute the cloud function, which can be distinguished by event.path
in the cloud function access source
Notice
From May 25, 2021, the value of the CNAME record of the domain name bound to Tencent Cloud will be adjusted from the default domain name to the `CNAME domain name' given by Tencent Cloud. The domain name that has been bound to normal use does not need to be adjusted
After filling in the domain name certificate in the previous step and the binding is successful, a CNAME domain name
will be returned. Set the CNAME record value of the bound domain name to this CNAME domain name
.
Notice
如需要更高的QPS支持,请发邮件到service@dcloud.io申请,邮件模板参考:申请解除限制邮件模板。若您还没有SSL证书,点此快速获取
About certificate content and private key
When applying for a certificate, there is usually a download option. After downloading the certificate, find the certificate corresponding to Nginx (including a crt file and a key file or a pem file and a key file), and open the crt/pem file in text form to see the certificate. content, the same key file corresponds to the private key. Consult the certificate issuer documentation for other cases.
example:
The ssl certificate applied for in Tencent Cloud contains a crt file and a key file. The text content of the crt is the certificate content, and the content of the key file is the private key.
The ssl certificate applied for on Alibaba Cloud contains a pem file and a key file. The text content of the pem is the content of the certificate, and the content of the key file is the private key.
Directly access the function through https://${cloud function Urlized domain name}/${path}
, where ${path}
is the configured function trigger path or its sub-path.
When using HTTP to access cloud functions, the HTTP request will be converted into a special structure, called integration request, the structure is as follows:
{
path: 'HTTP请求路径,如 /hello',
httpMethod: 'HTTP请求方法,如 GET',
headers: {HTTP请求头},
queryStringParameters: {HTTP请求的Query,键值对形式},
body: 'HTTP请求体',
isBase64Encoded: 'true or false,表示body是否为Base64编码'
}
Here is an example:
{
path: '/',
httpMethod: 'GET',
headers: {
'host': 'xxx.example.com',
'connection': 'close',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8'
},
isBase64Encoded: false,
body: ''
}
Example
Use GET to request https://${cloud function Urlized domain name}/${functionPath}?a=1&b=2
, the event
received by cloud function is
{
path: '/',
httpMethod: 'GET',
headers: {HTTP请求头},
queryStringParameters: {a: "1", b: "2"},
isBase64Encoded: false
}
Use POST request https://${cloud function Urlized domain name}/${functionPath}
, the event.body
received by cloud function is the data sent by the request, uni.request default content-type is application /json
// Take uni.request as an example
uni.request({
method: 'POST',
url: 'https://${云函数Url化域名}/${functionPath}',
data: {
a: 1,
b: 2
},
success(res) {
console.log(res);
}
})
// The event received by the cloud function is, note that if the data in this format is directly returned, it may be processed as an integrated response, refer to the integrated response document below
{
path: '/',
httpMethod: 'POST',
headers: {
...
"content-type": 'application/json'
},
isBase64Encoded: false,
body: '{"a":1,"b":2}', // 注意此处可能是base64,需要根据isBase64Encoded判断
}
Reference: urlized return value
The cloud object configuration using url still needs to follow the above steps, please refer to: url operation steps
When invoking a urlified cloud object, access the cloud object's method with a link in the form of url_path/cloud_object_method_name
. For example, the trigger path of the cloud object configuration is /todo
, and calling /todo/addTodo
will trigger the addTodo method of the cloud object. Methods are case-sensitive and cannot contain /
.
Before November 11, 2022, the access path can only end with the method name. After this time, it will be adjusted to allow the use of multi-segment paths to access cloud object methods. Still taking the above configuration as an example, both /todo/addTodo/self
and /todo/addTodo/group
will call the addTodo method of the cloud object.
The query part in the url will be converted into the input parameter of the cloud object method. Take the following todo cloud object as an example
module.exports = {
addTodo: function(params) {
console.log(params)
return {
errCode: 0
}
}
}
If the cloud object is called via https://xxx.com/todo/addTodo?title=todo-title&content=todo-content
, the console.log inside the todo method will output the following {title: 'todo-title', content: 'todo-content'}
It should be noted that the parameters parsed from the url are all string types.
Notice
_before
and _after
are executed normally when the cloud object is called by urlizationReference: urlized return value
Cloud functions and cloud objects can return string
, object
, number
and other types of data, or return Integration response, uniCloud will convert the return value into a normal HTTP response.
Cloud functions return strings, then:
exports.main = function() {
return 'hello gateway'
}
The final HTTP response is:
HTTP/1.1 200 OK
date: Mon, 16 Dec 2019 08:35:31 GMT
content-type: text/plain; charset=utf-8
content-length: 13
hello gateway
The returned Object
will be converted to JSON, and the content-type
of the HTTP response will be set to application/json
:
exports.main = function() {
return {
foo: 'bar'
}
}
The final HTTP response is:
HTTP/1.1 200 OK
date: Mon, 16 Dec 2019 08:35:31 GMT
content-type: application/json; charset=utf-8
content-length: 13
{"foo":"bar"}
Cloud functions can return an integrated response with a special structure like the following, to freely control the response body:
{
"mpserverlessComposedResponse": true, // 使用阿里云返回集成响应是需要此字段为true
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"body": "..."
}
Headers can return all response headers of traditional servers, including Set-Cookie, Content-Type, etc.
Set content-type
to text/html
to return HTML in body
, which will be automatically parsed by the browser:
Alibaba Cloud's default domain name cannot return html and display it in the browser, it can only trigger download (the Content-Disposition cannot be modified). There is no such restriction for binding a custom domain name
{
mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
statusCode: 200,
headers: {
'content-type': 'text/html'
},
body: '<h1>Hello</h1>'
}
The final HTTP response is:
HTTP/1.1 200 OK
date: Mon, 16 Dec 2019 08:35:31 GMT
content-type: text/html; charset=utf-8
content-length: 14
<h1>Hello</h1>
JavaScript files can be returned in body
by setting content-type
to application/javascript
:
{
mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
statusCode: 200,
headers: {
'content-type': 'application/javascript'
},
body: 'console.log("Hello!")'
}
The final HTTP response is:
HTTP/1.1 200 OK
date: Mon, 16 Dec 2019 08:35:31 GMT
content-type: application/javascript; charset=utf-8
content-length: 21
console.log("Hello!")
If the return body is a binary file such as image, audio and video, you can set isBase64Encoded
to true
, and convert the binary file content to a Base64 encoded string, for example:
{
mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
isBase64Encoded: true,
statusCode: 200,
headers: {
'content-type': 'image/png'
},
body: 'iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAY...'
}
The final HTTP response is a PNG image:
HTTP/1.1 200 OK
date: Mon, 16 Dec 2019 08:35:31 GMT
content-type: image/png
content-length: 9897
<binary payload...>
To redirect or return custom status codes such as 4xx, 5xx, etc., you can use the following methods
Note: The default domain name of Alibaba Cloud does not support the use of location in the returned header, and binding a custom domain name can be used normally
{
mpserverlessComposedResponse: false, // 使用阿里云返回集成响应是需要此字段为true
isBase64Encoded: false,
statusCode: 301,
headers: {
'location': 'http://www.baidu.com'
}
}
In some scenarios, cookies still play an important role, for example, in the case of URLization of cloud functions, to obtain the status of the client
Using cookies in cloud functions needs to rely on the cookie library npm page address, which can be installed through npm install cookie
Example of normal cloud function
'use strict';
//Introduce cookies
const cookie = require('cookie')
exports.main = async (event, context) => {
const cookieData = cookie.parse(event.headers.cookie || '')
//Set the cookie to the client
const cookieOptions = {
//Please refer to https://www.npmjs.com/package/cookie for specific parameters
maxAge: 60 * 60 * 24 * 7,//一周
path:"/"
}
const setCookieData = cookie.serialize('app', 'appName', cookieOptions)
return {
statusCode: 200,
headers: {
'content-type': '返回数据类型',
'set-cookie': setCookieData // 在headers内返回set-cookie用于设置客户端cookie
},
body: '返回数据'
}
};
Cloud Object Example
'use strict';
//Introduce cookies
const cookie = require('cookie')
module.exports = {
addTodo: function () {
const httpInfo = this.getHttpInfo()
const cookieData = cookie.parse(httpInfo.headers.cookie || '')
//Set the cookie to the client
const cookieOptions = {
//Please refer to https://www.npmjs.com/package/cookie for specific parameters
maxAge: 60 * 60 * 24 * 7,//一周
path:"/"
}
const setCookieData = cookie.serialize('app', 'appName', cookieOptions)
return {
statusCode: 200,
headers: {
'content-type': '返回数据类型',
'set-cookie': setCookieData // 在headers内返回set-cookie用于设置客户端cookie
},
body: '返回数据'
}
}
};
/test
as the cloud function url path, when accessing /test/a/b/c
, the path is /a/b/c
// cloud function
exports.main = function(event) {
let body = event.body
if(event.isBase64Encoded){
body = Buffer.from(body, 'base64').toString('utf8') // 将base64格式的xml内容转为xml字符串
}
}
// cloud object
module.exports = {
addTodo: function() {
let httpInfo = this.getHttpInfo()
let body = httpInfo.body
if(httpInfo.isBase64Encoded){
body = Buffer.from(body, 'base64').toString('utf8') // 将base64格式的xml内容转为xml字符串
}
}
}