Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Express Server无法从React本机应用获取请求_Javascript_Node.js_Json_React Native_Express - Fatal编程技术网

Javascript Express Server无法从React本机应用获取请求

Javascript Express Server无法从React本机应用获取请求,javascript,node.js,json,react-native,express,Javascript,Node.js,Json,React Native,Express,目标:创建可以相互通信的前端和后端。 我从前端开始使用https://reactnative.dev/movies.json作为占位符提供前端数据。成功完成后,我开始开发服务器,尽管它在Postman中工作,但在前端却无法工作 问题:当我更换https://reactnative.dev/movies.json与http://xxx.xxx.xxx.x:5000/movies.json后端和前端无法通信 到目前为止的测试: 我的react native应用程序可以成功地获取https://rea

目标:创建可以相互通信的前端和后端。 我从前端开始使用
https://reactnative.dev/movies.json
作为占位符提供前端数据。成功完成后,我开始开发服务器,尽管它在Postman中工作,但在前端却无法工作

问题:当我更换
https://reactnative.dev/movies.json
http://xxx.xxx.xxx.x:5000/movies.json
后端和前端无法通信

到目前为止的测试: 我的react native应用程序可以成功地
获取
https://reactnative.dev/movies.json
并将显示电影列表

我已经用Postman测试了后端,并验证了
http://xxx.xxx.xxx.x:5000/movies.json
返回与
完全相同的JSON响应https://reactnative.dev/movies.json

前端(工作-可以从
https://reactnative.dev/movies.json
):

/data/movies.json

{
    "title": "The Basics - Networking",
    "description": "Your app fetched this from a remote endpoint!",
    "movies": [
      { "id": "1", "title": "Star Wars", "releaseYear": "1977" },
      { "id": "2", "title": "Back to the Future", "releaseYear": "1985" },
      { "id": "3", "title": "The Matrix", "releaseYear": "1999" },
      { "id": "4", "title": "Inception", "releaseYear": "2010" },
      { "id": "5", "title": "Interstellar", "releaseYear": "2014" }
    ]
}
/routes/movies.js

const userRoutes = (app, fs) => {
    // variables
    const dataPath = "./data/movies.json";
    
    // READ
    app.get("/movies.json", (req, res) => {
        fs.readFile(dataPath, "utf8", (err, data) => {
        if (err) {
            throw err;
        }
        res.send(JSON.parse(data));
        });
    });
};

module.exports = userRoutes;
/routes/routes.js

// load up our shiny new route for users
const userRoutes = require("./movies");

const appRouter = (app, fs) => {
  // we've added in a default route here that handles empty routes
  // at the base API url
  app.get("/", (req, res) => {
    res.send("welcome to the development api-server");
  });

  // run our user route module here to complete the wire up
  userRoutes(app, fs);
};

// this line is unchanged
module.exports = appRouter;
server.js

// load up the express framework and body-parser helper
const express = require("express");
const bodyParser = require("body-parser");

// create an instance of express to serve our end points
const app = express();

// we'll load up node's built in file system helper library here
// (we'll be using this later to serve our JSON files
const fs = require("fs");

// configure our express instance with some body-parser settings
// including handling JSON data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// this is where we'll handle our various routes from
const routes = require("./routes/routes.js")(app, fs);

// finally, launch our server on port 5000.
const server = app.listen(5000, () => {
  console.log("listening on port %s...", server.address().port);
});
控制台错误输出:

Network request failed
- node_modules\whatwg-fetch\dist\fetch.umd.js:511:17 in setTimeout$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:135:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:387:16 in callTimers
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425:19 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:6 in __guard$argument_0- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
已更新服务器以使用HTTPS:

// load up the express framework and body-parser helper
const express = require("express");
const bodyParser = require("body-parser");
// create an instance of express to serve our end points
const app = express();

// we'll load up node's built in file system helper library here
// (we'll be using this later to serve our JSON files
const fs = require("fs");
const https = require('https');

// configure our express instance with some body-parser settings
// including handling JSON data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// this is where we'll handle our various routes from
const routes = require("./routes/routes.js")(app, fs);

// finally, launch our server on port 5000.
const server = https.createServer({
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert')
}, app).listen(5000, () => {
  console.log("listening on port %s...", server.address().port);
});
HTTPS更新后的控制台错误输出:

Network request failed
- node_modules\whatwg-fetch\dist\fetch.umd.js:505:17 in setTimeout$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:135:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:387:16 in callTimers
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425:19 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:6 in __guard$argument_0- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
HTTPS服务器的Postman中的测试结果:
GET
请求成功,但我必须设置邮递员以接受自签名证书

我运行了
expo-eject
以公开整个
Info.plist
NSAppTransportSecurity
的密钥和dict已在
Info.plist
中设置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>csharp_frontend</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0.0</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
      <key>NSExceptionDomains</key>
      <dict>
        <key>xxx.xxx.xxx.x</key>
        <dict>
          <key>NSExceptionAllowsInsecureHTTPLoads</key>
          <true/>
        </dict>
      </dict>
    </dict>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string/>
    <key>UILaunchStoryboardName</key>
    <string>SplashScreen</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
      <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
      <string>UIInterfaceOrientationPortrait</string>
      <string>UIInterfaceOrientationPortraitUpsideDown</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <false/>
    <key>UIStatusBarStyle</key>
    <string>UIStatusBarStyleDefault</string>
    <key>UIRequiresFullScreen</key>
    <true/>
  </dict>
</plist>
可能是问题:我认为由于SSL证书是自签名的,所以react本机前端将请求视为HTTP而不是HTTPS


有什么想法吗???

如果你在Android平台上运行并且使用API级别>27,那么我认为这个问题与Android中的http协议限制有关。如果是这样,您需要将android:usesCleartextTraffic=“true”添加到AndroidManifest.xml以允许http流量:

<?xml version="1.0" encoding="utf-8"?>
<manifest...>
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
    </application>
</manifest>

如果iOS版本>=8

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        ...
    </dict>
NSAppTransportSecurity
NSAllowsArbitraryLoads
...

console.log(错误)显示什么?
xxx.xxx.xxx.x
是IP地址吗?如果是这样,那么移动客户端是否在同一网络上也可能是这样,因为您已经从HTTPS转到了HTTP~Hi@Phil,我刚刚在
console.log(error)
输出中添加了它。是
xxx.xxx.xxx.x
表示我的IP地址,是的,移动客户端位于同一网络上。嗯,这是一个很好的发现,我在iOS上,可能是同一个问题,我会调查它并更新问题,如果这是解决方案。谢谢。好的,我没看到那个评论。您使用的是哪个iOS版本?Hi@TuanDucVo iOS软件版本13.5。1@DotNetFullStack您需要添加以下行:
NSAllowsArbitraryLoads
到info.plist当前正在查看@DotNetFullStack您在react native项目中看到该文件了吗?
      <dict>
        <key>xxx.xxx.xxx.x</key>
        <dict>
          <key>NSExceptionAllowsInsecureHTTPLoads</key>
          <true/>
        </dict>
      </dict>
Network request failed
- node_modules\whatwg-fetch\dist\fetch.umd.js:505:17 in setTimeout$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:135:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:387:16 in callTimers
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425:19 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
<?xml version="1.0" encoding="utf-8"?>
<manifest...>
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
    </application>
</manifest>
<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        ...
    </dict>