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 | class ExtensionSample { |
If you need to use a POST request or add custom headers, you can call the fetch API to implement it:
1 | class ExtensionSample { |
Tip: The URL must allow cross-origin requests (CORS); otherwise, no data can be accessed.
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 | class 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.