Taro: 编译成h5后,网络请求报错。小程序正常使用

Created on 27 May 2019  ·  6Comments  ·  Source: NervJS/taro

问题描述
编译成h5后,网络请求报错。小程序正常使用

httpUtil

import Taro, { arrayBuffer } from "@tarojs/taro";

enum HttpMethod {
  GET = "GET",
  POST = "POST"
}

const baseUrl = "https://xxxxx/apis";

// 动态获取header
const headers = () => {
  const access_token = Taro.getStorageSync("access_token") || "";
  const token_type = Taro.getStorageSync("token_type") || "";
  const currentPlatId = Taro.getStorageSync("currentPlatId") || "P00001";
  return {
    "Content-Type": "application/json; charset=UTF-8",
    authorization: `${token_type} ${access_token}`,
    source: `wx<>${currentPlatId}`
  };
};

const request = <T>(
  url: string,
  method: HttpMethod,
  parms?: {
    data?: object | string | arrayBuffer;
    header?: any;
  }
) => {
  Taro.addInterceptor(Taro.interceptors.logInterceptor);
  Taro.addInterceptor(Taro.interceptors.timeoutInterceptor);
  return new Promise<T>((resolve, reject) => {
    Taro.request({
      url: baseUrl + url,
      method: method,
      data: parms!.data,
      header: parms!.header || headers(), // 有些接口header需要另外传进来
      mode: "no-cors", // no-cors, cors, same-origin
      success: res => {
        const { statusCode = "", header = {}, data = {} } = res || {};
        if (statusCode >= 200 && statusCode <= 300) {
          Taro.setStorage({
            key: "response_time",
            data: new Date(header!.date)!.getTime() || 0
          });
          resolve(data!.data as T);
        } else if (statusCode == 401) {
          // 跳转登录
          Taro.navigateTo({
            url: "/pages/user/login/index?goback=1"
          });
          reject(new Error("登录失效,请重新登录"));
        } else if (statusCode == 500) {
          const msg = data!.msg;
          reject(new Error(msg));
        }
        reject(new Error("服务器正在维护中..."));
      },
      fail: err => {
        reject(err);
      }
    });
  });
};

const post = <T>(
  url: string,
  data?: object | string | arrayBuffer
): Promise<T> => {
  return request<T>(url, HttpMethod.POST, { data: data });
};

调用处

/**
 * 发送验证码动作
 */
serSendCode = async () => {
    if (!this.userName) {
      Taro.showToast({ title: "请输入手机号码", icon: "none", duration: 2000 });
      return;
    }
    try {
      Taro.showLoading({ title: "请等待...", mask: true });
      const data = await sendVerificationCode(this.userName);
      this.onCountDown(60);
      this.delay(INTERVAL);
    } catch (error) {
      Taro.showToast({ title: error.message, icon: "none", duration: 2000 });
      console.error(error.stack);
    } finally {
      Taro.hideLoading();
    }
};

/**
 * 发送验证码
 * @param mobile 手机号码
 */
export const sendVerificationCode = <T>(mobile: string) => {
  return post<T>("/operator/Sms/sendVerificationCode", { mobile });
};

webpack关于代理配置

const isH5 = process.env.CLIENT_ENV === "h5";
const HOST = '"https://xxxxxxx/apis/"';
module.exports = {
  defineConstants: {
    HOST: isH5 ? '"/api"' : HOST 
  },
  env: {
    NODE_ENV: '"development"'
  },
  defineConstants: {},
  weapp: {},
  h5: {
    devServer: {
      proxy: {
        "/api/": {
          target: JSON.parse(HOST),
          pathRewrite: {
            "^/api/": "/"
          },
          secure: false,
          changeOrigin: true,
          logLevel: "debug"
        }
      }
    }
  }
};

期望行为
接口调用成功

报错信息

index.js?3a5f:72 POST https://xxxxxxxxxxx/apis/operator/Sms/sendVerificationCode net::ERR_ABORTED 500
index.js?3a5f:83 Uncaught (in promise) SyntaxError: Unexpected end of input
    at eval (index.js?3a5f:83)
index.js?3a5f:83 Uncaught (in promise) SyntaxError: Unexpected end of input
    at eval (index.js?3a5f:83)

这是对应的源码信息
image

登录接口则是另外一个错误

Access to fetch at 'https://xxxxx/apis/auth/oauth/token?username=13910001000&grant_type=password&password=VCmruMH1d8Zu25oqq4E3Vg%3D%3D' from origin 'http://127.0.0.1:10086' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
TypeError: Failed to fetch
Uncaught (in promise) TypeError: Failed to fetch

系统信息

Taro v1.2 及以上版本已添加 taro info 命令,方便大家查看系统及依赖信息,运行该命令后将结果贴下面即可。

Taro CLI 1.3.0-beta.5 environment info:
System:
OS: macOS 10.14.4
Shell: 5.3 - /bin/zsh
Binaries:
Node: 11.10.0 - /usr/local/bin/node
npm: 6.9.0 - /usr/local/bin/npm
npmPackages:
@tarojs/async-await: ^1.3.0-beta.4 => 1.3.0-beta.4
@tarojs/components: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/mobx: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/mobx-h5: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/mobx-rn: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/plugin-babel: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/plugin-csso: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/plugin-less: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/plugin-sass: ^1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/plugin-uglifyjs: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/rn-runner: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/router: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/taro: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/taro-alipay: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/taro-h5: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/taro-swan: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/taro-tt: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/taro-weapp: 1.3.0-beta.3 => 1.3.0-beta.3
@tarojs/webpack-runner: 1.3.0-beta.3 => 1.3.0-beta.3
eslint-config-taro: 1.3.0-beta.3 => 1.3.0-beta.3
eslint-plugin-taro: 1.3.0-beta.3 => 1.3.0-beta.3
nervjs: ^1.4.0-beta.3 => 1.4.0-beta.4

Most helpful comment

问题是小程序的网络请求都是成功的 编译成h5就失败 我纳闷的是这个问题

500 的问题如果小程序没有出错,H5 出错可以看看是不是传参问题,比如 Content-Type 是不是 H5 和 Weapp 表现不一样之类的。

CORS 是浏览器的常见问题,具体可能出在你的 devServer 配置没配置好,建议跟着 Webpack 的文档检查一下配置,临时调试想忽略这个问题可以搜索一下浏览器插件,用 Allow-Control-Allow-Origin 这个名字一般都能搜到些,最关键的还是生环境允许 CORS,这个需要后端来配合了。

All 6 comments

欢迎提交 Issue~

如果你提交的是 bug 报告,请务必遵循 Issue 模板的规范,尽量用简洁的语言描述你的问题,最好能提供一个稳定简单的复现。🙏🙏🙏

如果你的信息提供过于模糊或不足,或者已经其他 issue 已经存在相关内容,你的 issue 有可能会被关闭。

Good luck and happy coding~

第一个 POST sendVerificationCode net::ERR_ABORTED 500 是 500 Internal Server Error,具体请联系你们后端联调解决。

第二个 Access to fetch at 'auth/oauth/token' from origin 'http://127.0.0.1:10086' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 是跨域请求(Cross-Origin Resource Sharing (CORS))错误,请联系你们后端联调解决。

问题是小程序的网络请求都是成功的 编译成h5就失败 我纳闷的是这个问题

问题是小程序的网络请求都是成功的 编译成h5就失败 我纳闷的是这个问题

500 的问题如果小程序没有出错,H5 出错可以看看是不是传参问题,比如 Content-Type 是不是 H5 和 Weapp 表现不一样之类的。

CORS 是浏览器的常见问题,具体可能出在你的 devServer 配置没配置好,建议跟着 Webpack 的文档检查一下配置,临时调试想忽略这个问题可以搜索一下浏览器插件,用 Allow-Control-Allow-Origin 这个名字一般都能搜到些,最关键的还是生环境允许 CORS,这个需要后端来配合了。

已经与后台同事沟通配置代理。确实是代理问题。谢谢解答

已经与后台同事沟通配置代理。确实是代理问题。谢谢解答

image
这个问题吗?

Was this page helpful?
0 / 5 - 0 ratings