HarmonyOS Web组件跨域请求问题

把离线H5包内置到HarmonyOS应用,但是未看到任何可以设置跨域请求的API,请问HarmonyOS web组件有该功能么,应该如何开启?

HarmonyOS
2024-11-07 11:14:27
986浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu

目前HarmonyOS解决跨域问题的解决方案,主要是通过拦截并自定义请求头的形式,可参考如下代码:

// xxx.ets 
import web_webview from '@ohos.web.webview' 
 
@Entry 
@Component 
struct WebComponent { 
  controller: web_webview.WebviewController = new web_webview.WebviewController() 
  responseweb: WebResourceResponse = new WebResourceResponse() 
  heads:Header[] = new Array() 
  @State webdata: string = "<!DOCTYPE html>\n" + 
    "<html>\n"+ 
    "<head>\n"+ 
    "<title>intercept test</title>\n"+ 
    "</head>\n"+ 
    "<body>\n"+ 
    "<h1>intercept test</h1>\n"+ 
    "</body>\n"+ 
    "</html>" 
  build() { 
    Column() { 
      Web({ src:'网络地址', controller: this.controller }) 
        .onInterceptRequest((event) => { 
          if (event) { 
            console.log('url:' + event.request.getRequestUrl()) 
          } 
          let head1:Header = { 
            headerKey:"Access-Control-Allow-Origin", 
            headerValue:"*" 
          } 
          let head2:Header = { 
            headerKey:"Cache-Control", 
            headerValue:"no-cache" 
          } 
          let length = this.heads.push(head1) 
          length = this.heads.push(head2) 
          this.responseweb.setResponseHeader(this.heads) 
          this.responseweb.setResponseData(this.webdata) 
          this.responseweb.setResponseEncoding('utf-8') 
          this.responseweb.setResponseMimeType('text/html') 
          this.responseweb.setResponseCode(200) 
          this.responseweb.setReasonMessage('OK') 
          return this.responseweb 
        }) 
    } 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.

其中的webdata 就是你返回的页面数据。如果觉得用string的形式返回webdata的形式维护麻烦,可以在拦截的过程中使用http请求,把请求的返回数据复制给webdata 同样能达到效果。

分享
微博
QQ
微信
回复
2024-11-07 17:14:55


相关问题
HarmonyOS web离线加载请求问题
1411浏览 • 1回复 待解决
HarmonyOS Web组件本地资源问题
588浏览 • 1回复 待解决
HarmonyOS web资源问题
825浏览 • 1回复 待解决
HarmonyOS web组件关闭拦截
650浏览 • 1回复 待解决
HarmonyOS webview组件问题
891浏览 • 1回复 待解决
Web组件如何访问资源?
956浏览 • 1回复 待解决
HarmonyOS webview问题
1651浏览 • 1回复 待解决
HarmonyOS Web本地资源加载异常
561浏览 • 1回复 待解决
HarmonyOS Web组件加载本地H5文件
1081浏览 • 1回复 待解决
iframe标签 src内部访问top问题
1043浏览 • 1回复 待解决