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.
$.ajax({
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);
$('#svg_img').html(data);
})
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
or
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.
Edit the service, and go to the “Manage API” tab.
Edit the API and select the “CORS is supported” checkbox.
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
- Fork this starter template
- A more advanced serverless machine learning example
Happy coding.