Angular前端托管在端口4200上。Express.js后端托管在端口4000上。两者都托管在我的台式计算机上。
现在,我在移动Android手机上,导航至192.168.1.X:4200以查看Angular应用程序。Angular应用程序可以加载并运行,但不会从Express.js服务器加载任何数据。在我的台式计算机上,对Express.js服务器的请求运行正常,并且浏览器中的Angular应用显示正确的数据。在两个设备的浏览器上访问192.168.1.X:4000(数据的API)将返回预期的JSON。
我通过USB将手机连接到台式计算机进行调试。这是Chrome DevTools控制台中的错误:
GET http://localhost:4000/ net::ERR_CONNECTION_REFUSED
和
ERROR
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:4000/", ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://localhost:4000/: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://localhost:4000/"
__proto__: HttpResponseBase
Chrome DevTools中的“网络”标签...
网络:
Name: localhost
Status: (failed)
Type: xhr
Initiator: zone-evergreen.js:2952
网络头:
General
Request URL: http://localhost:4000/
Referrer Policy: no-referrer-when-downgrade
Request Headers
Provisional headers are shown
Accept: application/json, text/plain, */*
Origin: http://192.168.1.2:4200
Referer: http://192.168.1.2:4200/
Save-Data: on
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Linux; Android 9; SM-G965W) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.92 Mobile Safari/537.36
Express.js代码:
const express = require('express'),
cors = require('cors');
const app = new express();
app.use(cors());
app.get('/', async (req, res) => {
res.json({data: "a lot of data"});
});
app.listen(4000, () => {
console.log('Back-end listening on port: 4000')
});
因此,通过电话而不是通过台式机访问Angular应用程序时,对Express.js服务器的请求失败。
看起来当您从Angular代码向要localhost
用作IP地址的Express服务器发出请求时。由于Express.js应用程序在本地PC上运行,因此可以在您的PC上使用。但是,当角度应用程序在移动设备上运行时,它将无法访问您的快递服务器。您可以做的是,而不是发出localhost
使用ip地址的请求192.168.1.X:4000
。这样,即使在移动浏览器上查看角度时,请求也将到达快递服务器。
希望能有所帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句