Node.js 无法从节点API获取数据
我有一个使用node的API(Localhost:3000)和一个使用angular6的前端(Localhost:4200)。使用我的常规chrome浏览器,我能够在API中对数据库进行CRUD,但当我使用android emulator时(10.0.2.2:4200),我无法再对数据库进行任何CRUD。请参阅下面我的代码: 节点[index.js]Node.js 无法从节点API获取数据,node.js,angular,Node.js,Angular,我有一个使用node的API(Localhost:3000)和一个使用angular6的前端(Localhost:4200)。使用我的常规chrome浏览器,我能够在API中对数据库进行CRUD,但当我使用android emulator时(10.0.2.2:4200),我无法再对数据库进行任何CRUD。请参阅下面我的代码: 节点[index.js] const express = require("express"); const nedb = require("nedb");
const express = require("express");
const nedb = require("nedb");
const rest = require("express-nedb-rest");
const cors = require("cors");
const app = express();
const datastore = new nedb({
filename: "mycoffeeapp.db",
autoload: true
});
const restAPI = rest();
restAPI.addDatastore('coffees', datastore);
app.use(cors());
app.use('/', restAPI);
app.listen(3000);
角度前端
这在data.service中
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Injectable({
providedIn: "root"
})
export class DataService {
public endpoint = "http://localhost:3000";
constructor(
private http: HttpClient
) {}
getList(callback) {
this.http.get(`${this.endpoint}/coffees`)
.subscribe(response => {
callback(response);
});
}
get(coffeeId: string, callback) {
this.http.get(`${this.endpoint}/coffees/${coffeeId}`)
.subscribe(response => {
callback(response);
});
}
save(coffee, callback) {
if (coffee._id) {
this.http.put(`${this.endpoint}/coffees/${coffee._id}`, coffee)
.subscribe(response => {
callback(true);
});
} else {
this.http.post(`${this.endpoint}/coffees`, coffee)
.subscribe(response => {
callback(true);
});
}
}
}
在组件中:
constructor(
private data: DataService,
private router: Router,
private gls: GeoLocationService
) { }
ngOnInit() {
this.data.getList(list => {
this.list = list;
});
}
如果您运行模拟的android设备,并尝试在
10.0.2.2:4200
上访问您的开发环境,您将能够访问angular应用程序,前提是该模拟器位于同一网络上
现在,您需要确保您的API可以从本地计算机外部访问,并且在前端使用IP地址设置API url
export class DataService {
public endpoint = "http://10.0.2.2:3000";
如果您使用
localhost
,这将指向仿真设备本身,它没有让您运行API,我不确定我是否完全遵循。您是否在chrome浏览器中的模拟android设备上运行angular前端?您的帖子缺少一个问题。您是否也可以添加观察到的行为、任何错误?缺少值?您可能需要为API指定IP地址,而不是“http://localhost:3000“
,例如http://10.0.2.2:3000
您能发布浏览器控制台中可见的错误吗?@ErwinLengkeek不,先生。我正在从android studio运行模拟器。如果我在桌面浏览器上使用“”,我将无法再从节点服务器获取数据。但我现在可以在android emulator中看到它。有什么方法可以在桌面浏览器和android模拟浏览器中看到它吗?@Ibanez1408这应该也可以在您的桌面浏览器中看到。除非你有一些代理设置阻止你这么做,否则我不会使用任何代理。我只是无法让桌面浏览器与10配合使用。系列但是,如果我使用localhost或127.0.0.1,我的桌面浏览器可以工作,但android不能。这是我在检查“get net::ERR\u CONNECTION\u TIMED\u OUT”时遇到的错误