# scenes to be used

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.

  • Scenario 1: For example, WeChat payment on the App side needs to be configured with a server callback address. In this case, an HTTP URL is required.
  • Scenario 2: For a system not developed by uni-app, if you want to connect to uniCloud and read and write data, you also need to access it through HTTP URL.

The following points need to be paid attention to after urlization

  • Security: To ensure business security, developers need to implement permission control and security protection in the code to prevent unauthorized access from triggering sensitive operations.
  • Billing: After the cloud function has URLization enabled, if a large number of malicious accesses are encountered and cloud function resources are consumed, the developer can set the cloud function access address to empty to stop HTTP access support.

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

  • Tencent Cloud free service space only supports configuration of up to 10 cloud function URL addresses

# Operation steps

# Set cloud function HTTP access address

  1. Log in to uniCloud background, and select the service space.
  2. Click [Cloud Function] on the left menu bar to enter the cloud function page.
  3. Click the [Details] button of the cloud function to be configured to configure the access path.

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

  • When Alibaba Cloud uses the default domain name, accessing the urlized address in the browser will trigger the download. Binding a custom domain name does not have this problem

# Bind custom domain name

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

  1. Click [Cloud Function] on the left menu bar to enter the cloud function page.
  2. Click [Cloud Function Domain Name Binding] to configure in the pop-up configuration window.

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

  • Each service space can be bound with at most 1 custom domain name
  • uniCloud provides a default domain name for experience and testing of this feature
  • It should be noted that the bound domain name must have been filed
  • A single service space of Tencent Cloud can support QPS to receive the QPS limit of the service space, refer to: Package Resources
  • 阿里云单个服务空间可支持被访问的最大 QPS 为1000(具体频次受函数并发限制)
  • Alibaba Cloud binds a custom domain name to require the domain name to retain filing information in Alibaba Cloud, refer to: Add filing information

如需要更高的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.

# Common cloud function

# Access cloud functions via HTTP URL

Directly access the function through https://${cloud function Urlized domain name}/${path}, where ${path} is the configured function trigger path or its sub-path.

# Cloud function input parameters

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判断
}

# Cloud function urlize return value

Reference: urlized return value

# Cloud objects use urlized

The cloud object configuration using url still needs to follow the above steps, please refer to: url operation steps

# Access cloud objects via HTTP URL

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.

# Cloud object input parameter

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 urlization
  • If you need to get the parameters passed to the cloud object in other ways (eg: post a json content to the cloud object), please use this.getHttpInfo to get it

# Cloud object urlized return value

Reference: urlized return value

# 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.

# return string or number

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

# return Object

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"}

# Return integration response

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.

# Return HTML with integrated response

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>

# Return JS file with integrated response

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!")

# Return binary with integrated response

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...>

# return different status codes

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: '返回数据'
    }
  }
};

# Notes

  • Alibaba Cloud currently has the following restrictions on requests and responses
    • Request Body size limit, which cannot exceed 1MB.
    • Respond to the body size limit, which cannot exceed 1MB.
  • Tencent Cloud currently has the following restrictions on requests and responses
    • Request Body size limit, text cannot exceed 100KB, and binary cannot exceed 20MB.
    • Respond to the Body size limit, which cannot exceed 6MB.
  • In the urlization scenario, path (cloud function event.path, cloud object httpInfo.path) indicates the access path with the configured urlization path as the root path. To configure /test as the cloud function url path, when accessing /test/a/b/c, the path is /a/b/c
  • In URLized scenarios, information such as client platform cannot be obtained, but client IP and client userAgent can be obtained.
  • The request body of the received post request may be converted to base64, if so, a conversion is required. Take receiving post requests in text/xml format as an example
    // 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字符串
            }
        }
    }