文档开发者中心
我的

http和fetch接口进行https请求正常,http请求失败,已配置cleartextTraffic为true

http请求相关配置已经按照文档配置好了,当请求url为https可以正常请求,但是请求本地通过express启动的node服务却失败了,而失败code为200,失败信息为“request data error”。

1、项目config.json

收起
自动换行
深色代码主题
复制

{ "app": { "bundleName": "com.example.ohos_demo.hmservice", "vendor": "example", "version": { "code": 1000000, "name": "1.0.0" } }, "deviceConfig": { "default": { "network": { "cleartextTraffic": true } } }, "module": { "package": "com.example.ohos_demo", "name": ".MyApplication", "mainAbility": "com.example.ohos_demo.MainAbility", "deviceType": [ "phone", "tablet", "car" ], "distro": { "deliveryWithInstall": true, "moduleName": "entry", "moduleType": "entry", "installationFree": true }, "abilities": [ { "skills": [ { "entities": [ "entity.system.home" ], "actions": [ "action.system.home" ] } ], "visible": true, "name": "com.example.ohos_demo.MainAbility", "icon": "$media:icon", "description": "$string:mainability_description", "label": "$string:entry_MainAbility", "type": "page", "launchType": "standard" } ], "reqPermissions": [ { "name": "ohos.permission.INTERNET", "reason": "using axios", "usedScene": { "ability": [ "com.example.ohos_demo.MainAbility", "com.example.ohos_demo.MyApplication" ] } } ], "js": [ { "mode": { "syntax": "ets", "type": "pageAbility" }, "pages": [ "pages/index" ], "name": "default", "window": { "designWidth": 720, "autoDesignWidth": false } } ] }}

2. ets页面


收起
自动换行
深色代码主题
复制

import http from '@ohos.net.http'import fetch from '@system.fetch';@Entry@Componentstruct Index { build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Text('Hello World') .fontSize(50) .fontWeight(FontWeight.Bold) Button() { Text("http request") .fontSize(30) .onClick(() => { let httpRequest = http.createHttp();// let url = "https://www.baidu.com" // 正常请求 const url = 'http://localhost:3000/get/info'// 请求报错 httpRequest.request(url, function handleResponse(err, data) { console.info('### get info by http') if (!err) { console.info('### request success') console.info('### data.result = ' + data.result + ".") } else { console.info('### err.data = ' + err.data) // request data error console.info('### err.code = ' + err.code) // 200 } }) }) } Button() { Text("fetch request") .fontSize(30) .onClick(() => { let url = 'http://localhost:3000/get/info' fetch.fetch({ url: url, success: function(response) { console.info('### get info by fetch') console.info("### responseData = " + response) }, fail: function(err) { console.info('### err.data = ' + err) } }) }) } } .width('100%') .height('100%') }}

3、node服务 app.js

收起
自动换行
深色代码主题
复制

const express = require('express')const fs = require('fs')const bodyParser = require('body-parser')const app = express()app.use(bodyParser.urlencoded({extended: false}))app.use(bodyParser.json())const cors = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': true, 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type'}app.get('/get/info', function (req, res) { res.set(cors) res.send('Got a GET request at /get/info')})app.post('/post/info', function (req, res) { console.log('*** ' + JSON.stringify(req.body)); res.send('Got a POST request at /post/info')})var server = app.listen(3000, function () { console.log('开启成功!')})

点赞
收藏
回复
5
分享
举报
浏览1838 发布于2021-12-15 02:28未知归属地
全部评论
最多点赞
最新发布
最早发布
已解决,不能直接请求 localhost url。需要映射到公网地址,然后访问就可以了。
2
2楼回复于2021-12-16 08:00 未知归属地
  • 155******67
    你好 你是用的本地虚拟机吗?
    2022-03-15 08:03 未知归属地
  • 155******67
    如何映射的
    2022-03-15 08:07 未知归属地

你好,请参考下面代码

 private httpRequest() {

       var that = this;

       let httpRequest= http.createHttp();

       httpRequest.request(uri, {

           method:http.RequestMethod.GET,

           header: {

               'Content-Type': 'application/json'

           },

           readTimeout: 60000,

           connectTimeout: 60000

       },(err, data) => {

           that.httpResult = "请求成功"

           if (!err) {

               that.httpResult = JSON.stringify(data.result)

               console.info('=============结果:' + JSON.stringify(data.result));

           } else {

               that.httpResult = "请求失败"

           }

       });

   }

展开全部
3楼回复于2021-12-17 01:10 未知归属地
欢迎开发小伙伴们进来帮帮楼主
1楼回复于2021-12-15 02:45 未知归属地
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要发帖子

了解社区公约,与您携手共创和谐专业的开发者社区。