Wings Engine

URL Request in Secondary Development

1. Fetch Function

Sometimes, we need to make independent data requests, submit data, or even perform reverse control of IoT devices. In secondary development, we often need to request URLs directly. Currently, Wings Engine supports using the fetch function to request URLs. For detailed information on the fetch API, refer to the official documentation: Fetch API - Using Fetch

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

In Wings Engine, using fetch is no different from using it in native JavaScript. Below is a simple example of a fetch request:

1
2
3
4
5
6
7
8
9
10
11
12
13
class ExtensionSample {
init() {
this.element.addEventListener("click", async () => {
//The URL must allow cross-origin requests
const response = await fetch("http://www.example.com/get");
//If the response is in JSON format, use response.json()
//If it's plain text, you can write it as response.text()
const data = await response.json();
console.log(data);
});
}
}
export default ExtensionSample;

If you need to use a POST request or add custom headers, you can call the fetch API to implement it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class ExtensionSample {
init() {
this.element.addEventListener("click", async () => {
//The URL must allow cross-origin requests
const response = await fetch("http://www.example.com/post", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
//If the response is in JSON format, use response.json()
//If it's plain text, you can write it as response.text()
const data = await response.json();
console.log(data);
});
}
}
export default ExtensionSample;

Tip: The URL must allow cross-origin requests (CORS); otherwise, no data can be accessed.

2. Cross-Origin Issues

When using fetch to request a URL, if the URL itself does not allow cross-origin access, you will encounter a CORS error during runtime. For example, in the following code:

1
2
3
4
5
6
7
8
9
10
11
class ExtensionSample {
init() {
this.element.addEventListener("click", async () => {
//The URL must allow cross-origin requests
const response = await fetch("https://www.baidu.com/");
const data = await response.json();
console.log(data);
});
}
}
export default ExtensionSample;

In the browser, you may see an error like:

In such cases, you need to modify the server-side code by adding the following to the returned headers:

1
Access-Control-Allow-Origin: The requested Host + port number

This header allows cross-origin requests, solving the CORS issue. However, in this example, since the request is to another server that you do not control, it’s not possible to modify the server’s code. Therefore, the fetch function must be used with APIs on servers that you can modify.