自签名证书React Native

时间:2018-06-16 23:22:46

标签: react-native react-native-android redux-saga

我尝试在React Native中的调用API中导入自签名证书(certificate.crt),但每次都有同样的错误:

Unable to resolve module `../certificate.crt`

我正在使用Redact和Redux Saga的React Native

import axios from "axios";

const casert = require("../certificate.crt");

const API_URL = "MY_IP_SERVER";

export function callGetApi(url, param) {
    return axios({
    method: "get",
    ca: casert,
    url: `${API_URL}${url}${param}`,
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
});
}

文件树是这样的:

Project file tree

如果有人知道如何包含此自签名证书,因为API需要在标头中接受任何请求。

由于

2 个答案:

答案 0 :(得分:0)

当您使用axios时,请查看:

  

How can I make a HTTPS to the backend with a self-signed certificate?

完成所有步骤,然后你就会有这样的事情:

  <Button onPress={
    ()=>{
      const x = axios.create({
        baseURL: 'https://api.realtycoast.io/',
        timeout: 10000,
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        }
      });
    x.request({
      url: '/user/123'
    })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    }
  }>
    <Text>Axios Test</Text>
  </Button>

答案 1 :(得分:0)

我找到了一个答案的开头:https://github.com/axios/axios/issues/1495

import axios from "axios";

const API_URL = "HTTPS://MY_IP_SERVER";

export function callGetApi(url, param) {
    return axios({
        method: "get",
        httpsAgent: new https.Agent({
            ca: fs.readFileSync("../certificate.crt"),
        }),
        url: `${API_URL}${url}${param}`,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    });
}

知道,证书是包含但在我的saga函数中,当我尝试执行API调用时直接进入catch异常

export function* loginRequest(payload) {

    yield takeEvery(authActions.LOGIN_REQUEST, function*(payload) {
        try {

            console.log("Email Saga : " + payload.email);
            let response = null;

            response = yield call(requestUUID, "account/uuid/email/", payload.email);
            const uuid = response.data.uuid;

            debugger;

            yield put({ type: "LOGIN_SUCCESS" });
        } catch (error) {
            debugger;
            yield put({ type: authActions.LOGIN_ERROR });
        }
    });
}