SoFunction
Updated on 2025-04-04

Resolve cross-domain problem in UniApp WebView page

1. Overview

The WebView component in UniApp can use local web pages and web pages.

During the process of using local web pages, sending requests will cause cross-domain problems, and you will find that through packet captureOriginThe value of the request header is"null"

Request sample code

// Create xhr objectvar xhr = new XMLHttpRequest();
// Create a PUT request, using asynchronous('PUT', 'http://192.168.1.47:8086/load_balance/test', true);
// Register related events = (event) => { 
  ("event=====", event)
};
 = (error) => { 
    ("error=========", error)
};
// Send a request();

2. Solution

In the above example code, if the backend does not perform cross-domain processing, the request will not be accessed normally. Why does cross-domain problem occur?OriginWhy is the value of the request header so strange?

In fact, we can get the answer by checking the browser address bar information and printingWe can see the following results for the value of

View the value of the address bar

("====", );
// ==== file:///var/mobile/Containers/Data/Application/7084A02A-514F-4B7B-A966-F610315939C1/Documents/Pandora/apps/B01189FFE7E81940832DDC748B2EDE9E/www/hybrid/html/

We can find that the local web page is accessed through the file:// protocol and is not the http protocol. Therefore, when we send an http request, this request does not comply with the same-origin policy.

Since there is no information such as domain names and ports in the file protocol,OriginThe value of the request header will be"null"

After knowing the reason, we can actually make the backend set to allow "null" to cross-domain, but it will feel weird to do so.

There is another way to solve this problem directly on the front end without using the back end.

It is to use the 5+ APIObject, this request object is specially used to solve cross-domain problems.

So, let's modify the above example code.

Request sample code (no cross-domain trigger)

// Remember to call the plus object after the plusready event is completed('plusready', () =>{
    // Create xhr object using    var xhr = new ();
    // Create a PUT request, using asynchronous    ('PUT', 'http://192.168.1.47:8086/load_balance/test', true);
    // Register related events     = (event) => {
        ("event=====", event)
    };
     = (error) => {
        ("error=========", error)
    };
    // Send a request    ();
})

UsedAfter the object, there will be no cross-domain problems.

Summarize

This is the article about requesting cross-domain problem solving in UniApp WebView page. For more related UniApp WebView page requesting cross-domain content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!