CORS Issues for MATLAB Compiler SDK Microservices on Google Cloud
Mostrar comentarios más antiguos
Following the doc above, I successfully compiled a MATLAB function into a docker image and hosted it into Google Cloud. I can see the "curl" command works in Windows' cmd and can get the JSON formatted result like the doc.
Now, I wanted to make an HTML file and tried to use JavaScript to run REST API like I did for cmd. However, it gives me error like this:
Access to fetch at 'https://DomainName/financetools/simpInterest' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I found that this error is related to CORS, but I have no idea where I can make such a change in case of MATLAB. What further steps should I take to handle the issue?

Below is my HTML script to work with JS for REST API.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>REST API Example</title>
</head>
<body>
<h1>Simple Interest Calculator</h1>
<button onclick="calculateInterest()">Calculate Interest</button>
<div id="result"></div>
<script>
async function calculateInterest() {
// Change the DomainName to your Google Cloud Run's URL.
const url = "https://DomainName/financetools/simpInterest";
const data = {
nargout: 1,
rhs: [21000, 0.043, 12]
};
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
const result = await response.json();
// Assuming the structure is {"lhs":[{"mwdata":[10836],"mwsize":[1,1],"mwtype":"double"}]}
const interest = result.lhs[0].mwdata[0];
document.getElementById("result").innerText = `Calculated Interest: ${interest}`;
} catch (error) {
console.error("Error:", error);
document.getElementById("result").innerText = "An error occurred while calculating interest.";
}
}
</script>
</body>
</html>
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Microservices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

