【问题标题】:React Native fetch https Node js serverReact Native 获取 https 节点 js 服务器
【发布时间】:2021-09-08 17:30:52
【问题描述】:

我真的需要这方面的帮助:

我在这里构建了我的第一个节点 js 服务器:

var express = require('express'),
app = express(),
https = require('https');
port = process.env.PORT || 443,
mongoose = require('mongoose'),
Task = require('./api/models/myCarModel'), 
bodyParser = require('body-parser');
fs = require("fs");

const options = {
key: fs.readFileSync('./static/HttpsFile/privatekey.pem').toString(),
cert: fs.readFileSync('./static/HttpsFile/certificate.pem').toString(),

};


mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Tododb'); 


app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var routes = require('./api/routes/myCarRoutes'); //importing route
routes(app); //register the route

https.createServer(options, app).listen(port);

console.log(options.key)
console.log('RESTful API server started on: ' + port);

这是我简单的 react-native 应用主页:

import React, { useState } from 'react';
import { useEffect } from 'react';
import { Button, StyleSheet, Text, TextInput, View } from 'react-native';

const Home = () => {

const [text, setText] = useState('');

useEffect(()=> {
    debugger
    fetch('https://192.168.1.8:443/cars', {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json'
        }})
        //axios.get("https://192.168.1.8:3000/cars")
        .then((res:any) => {
        debugger;
    }, (err:any) => {
        console.log(err)
        debugger;
    })

}, [])

 return(...etc...)

现在: 当我第一次使用邮递员测试 API 时,我收到关于使用自签名证书(我通过 OpneSSL 使用)的错误。我恳请 Postman 接受这个想法,一切都很顺利。 这不是 react-native 的情况: 我正在使用 expo,在我的 android 手机上测试我的应用程序,当我调试 API 调用时,我在错误中收到以下错误:“TypeError: Network request failed”。

我不想通过让 Android 接受 HTTP 协议来解决问题。

大家好

【问题讨论】:

    标签: node.js react-native types https openssl


    【解决方案1】:

    所以您正在手机上运行该应用程序?您的手机无权访问您在计算机上运行的服务器。 “https://192.168.1.8:443/cars”只有在您尝试在同一设备上连接时才能访问(它可能是您计算机上运行的模拟器)。但是,如果您使用内部设备,这仍然可能不起作用。在这种情况下,您可以通过http://10.0.2.2:433 访问它(这对我有用)。

    加分项:Https 在本地计算机上不起作用。由于它无法验证请求。在本地测试时使用“http”。

    【讨论】:

    • 我的猜测是,经过进一步研究,需要通过 openSSL 自签名证书找到一种解决方法,以便在本地环境中测试 https。
    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    相关资源
    最近更新 更多