HTTP Request

In some cases, it may be necessary to make requests to a server to fetch data. In Cocos Creator, you can use the fetch method, which is part of JavaScript.

The prototype is defined as follows.

  1. declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;

Setting Up a Test Sever

First, set up a simple HTTP server using a backend language you are familiar with. Non-backend developers can skip this section. In this example, we’ll use Golang to set up the server. Here is an example code:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. )
  7. func handler(w http.ResponseWriter, r *http.Request) {
  8. fmt.Fprintf(w, "http request received")
  9. }
  10. func main() {
  11. http.HandleFunc("/", handler)
  12. log.Fatal(http.ListenAndServe(":8080", nil))
  13. }

The above code will set up a network server listening on port 8080.

Making an HTTP Request

In Cocos Creator, you can use the fetch method to make requests to the server. In this example, we’ll use the GET method to request data from the server and expect the server to respond with text data. Here’s an example code:

  1. import { _decorator, Component } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('HttpTest')
  4. export class HttpTest extends Component {
  5. start() {
  6. fetch("http://127.0.0.1:8080").then((response: Response) => {
  7. return response.text()
  8. }).then((value) => {
  9. console.log(value);
  10. })
  11. }
  12. }

After running the scene, the following log will be printed:

  1. > http request received.

You can also use response.json() to retrieve the response in JSON format.

You can refer to the MDN Web Docs for more detailed information.