Enable AJAX access for Tencent Serverless Cloud Functions

• 2 minutes to read

An important use case of serverless functions is to act as endpoints for AJAX calls from HTML web pages. This way, we can build truly “serverless” web applications with static HTML + JS pages on the front end, and serverless functions on the backend. A good example is this web page for fitting and plotting eigenvectors, a common machine learning task, on a 2-D data set.

The web page calls a WebAssembly-based Tencent Serverless Cloud Function via AJAX. The JS code in the web page is as follows. The url is the API Gateway Trigger we defined for our cloud function.

  method: "POST",
  url: "https://service-m9pxktbc-1302315972.hk.apigw.tencentcs.com/release/PCASVG",
  data: $('#csv_data').val(),
  dataType: "text"
}).done(function(data) {
  $('#fitplot').prop('disabled', false);

However, the above code does not quite work out of the box. The browser's JavaScript console shows the following error message.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource


Reason: CORS header 'Access-Control-Allow-Origin' missing

In order to fix this problem, you must enable CORS on the Tencent Cloud API Gateway for the serverless function.

Enable CORS on Tencent API Gateway

Go to the API Gateway management console and click on “Service”. Locate the API gateway service you created as the “trigger” for your serverless function.

Find the API gateway service for your serverless function

Edit the service, and go to the “Manage API” tab.

Manage API

Edit the API and select the “CORS is supported” checkbox.

Check CORS support

Now save the settings, and then remember to publish this service again.

Next steps

Learn more about Rust and WebAssembly serverless functions on Tencent Cloud

Happy coding.

A high-performance, extensible, and hardware optimized WebAssembly Virtual Machine for automotive, cloud, AI, and blockchain applications