Enable CORS for a REST API Resource

Cross-region Resource Sharing (CORS) is a browser security feature that restricts cross-region HTTP requests that are initiated from scripts running in the browser. If you can not access API and receive an error message indicating the cross-region request was blocked, you need to enable CORS. This topic describes how to enable CORS for a simple request.

Example

We take the Login interface as an example to describe how to allow CORS with JavaScript.

//Define the request URL
const url = "http://api.yeastarcloud.com/api/v1.1.0/login";

//Set the Content-Type header with specific value
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded"); //The content type must be one of "application/x-www-form-urlencoded", "multipart/form-data", or "text/plain". In this way, the request will be considered as a "simple request", which doesn't require a preflight request (preliminary checks) before being initiated.

//Define Body parameters
const raw = JSON.stringify({
    "username": "api",
    "password": "2d7257a528679d01a19c70e3fa773620",
    "port": "8260",
});

//Define request options
const requestOptions = {
    method: "POST", 
    mode: "cors", //This indicates that the request should be made with CORS enabled.
    headers: myHeaders,
    body: raw, 
    credentials: "include", //The browser will include cookies in the request headers, allowing the server to authenticate and authorize the request based on the provided credentials.
};

//In this example, use fetch() to make an HTTP request to the specified URL with the given options.
fetch(http://api.yeastarcloud.com/api/v1.1.0/login, requestOptions)
    .then((response) => response.text())
    .then((result) => console.log(result))
    .catch((error) => console.error(error));