taro 请求及H5跨域请求 Taro.request(option)

燃烧的冰2022-06-19  6.7K+

data 参数说明 最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。

转换规则如下:

  • 对于 GET 方法的数据,会将数据转换成 query string(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...)
  • 对于 POST 方法且 header['content-type'] 为 application/json 的数据,会对数据进行 JSON 序列化
  • 对于 POST 方法且 header['content-type'] 为 application/x-www-form-urlencoded 的数据,会将数据转换成 query string (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...) 
Taro.request({
  url: '/api/index-1.html', // API请求接口,不需要域名
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' // 默认值
  },
  success: function (res) {
    console.log(res.data)
  }
})

H5端如果不跟API服务端在一个域名下会遇到跨域请求的问题,按照以下配置修改 devServer 部分

以下配置为跨域请求代理转发模式

config/index.js

const Domain = 'http://www.x.com'; // 请求域名

const config = {
  projectName: 'miniapp',
  date: '2022-6-19',
  designWidth: 750,
  deviceRatio: {
    640: 2.34 / 2,
    750: 1,
    828: 1.81 / 2
  },
  sourceRoot: 'src',
  outputRoot: 'dist',
  plugins: [],
  defineConstants: {
  },
  copy: {
    patterns: [
    ],
    options: {
    }
  },
  framework: 'react',
  mini: {
    postcss: {
      pxtransform: {
        enable: true,
        config: {

        }
      },
      url: {
        enable: true,
        config: {
          limit: 1024 // 设定转换尺寸上限
        }
      },
      cssModules: {
        enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
        config: {
          namingPattern: 'module', // 转换模式,取值为 global/module
          generateScopedName: '[name]__[local]___[hash:base64:5]'
        }
      }
    }
  },
  h5: {
    publicPath: '/',
    staticDirectory: 'static',
    postcss: {
      autoprefixer: {
        enable: true,
        config: {
        }
      },
      cssModules: {
        enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
        config: {
          namingPattern: 'module', // 转换模式,取值为 global/module
          generateScopedName: '[name]__[local]___[hash:base64:5]'
        }
      }
    },
    // 设置代理服务器转发
    devServer: {
      proxy: {
        '/api/': {
          target: Domain,
          pathRewrite: {
            '^/api/': '' // 所以带有/api/请求的链接一律替换为空并追加域名请求
          },
          changeOrigin: true
        }
      }
    }
  }
}

module.exports = function (merge) {
  if (process.env.NODE_ENV === 'development') {
    return merge({}, config, require('./dev'))
  }
  return merge({}, config, require('./prod'))
}
转载请注明原文地址:http://www.wellcms.cn/read-263.html
0