HarmonyOS Web组件跨域的问题?

使用web组件加载url时,遇到了跨域的问题。入口url是本地资源,然后在本地的js中调用了一个https的请求,报了跨域的错误。

错误日志如下:

"Access to XMLHttpRequest at 'xxx' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.", source: file:///data/storage/el2/base/haps/TPlusApp/files/lightApp/18/index.html (0)

请问,需要如何处理这个问题?查过相关文档,说http的允许跨域,还有一个解决本地资源跨域问题的,解决的也是本地和本地的跨域,这种情况需要如何处理?

阅读 484
1 个回答

跨域处理接口setPathAllowingUniversalAccess。

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-webview-V5\#setpathallowinguniversalaccess12在resource目录下创建文件夹resfile,将需要的跨域html文件放这个目录下。

import web_webview from "@ohos.web.webview";
import { BusinessError } from '@kit.BasicServicesKit';

@Preview
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  webviewController: web_webview.WebviewController = new web_webview.WebviewController();
  aboutToAppear() {
    // 配置Web开启调试模式
    web_webview.WebviewController.setWebDebuggingAccess(true);
  }
  build() {
    RelativeContainer() {
      Web({
        src: '',
        controller: this.webviewController
      })
        .onControllerAttached(() => {
          try {
            // 设置允许可以跨域访问的路径列表
            this.webviewController.setPathAllowingUniversalAccess([
              getContext().resourceDir+"/test",
              getContext().filesDir + "/example"
            ])
            this.webviewController.loadUrl("file://" + getContext().resourceDir + "/test/index.html")
          } catch (error) {
            console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
          }
        })
        .javaScriptAccess(true)
        .fileAccess(true)
        .domStorageAccess(true)
        .id('HelloWorld')
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
    }
    .height('100%')
    .width('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进