我目前正在使用 Angular6 创建一个 CRUD 应用程序使用 MSSQL。
我已成功从本地数据库检索数据并创建所需的路线,但在前端显示数据时遇到问题。
//masterList.service.ts
import {
Injectable
} from '@angular/core';
import {
HttpClient
} from '@angular/common/http';
import {
MasterList
} from './MasterList';
@Injectable({
providedIn: 'root'
})
export class MasterListService {
uri = 'http://localhost:4000/masterList';
constructor(private http: HttpClient) {}
getMasterList() {
console.log(this);
return this
.http
.get(`${this.uri}/`);
}
}
//package.json
"name": "ng6crud",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "nodemon server.js && ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
运行:
npm 启动
这将返回带有数据的服务,但应用程序未编译,颠倒顺序会产生相反的效果,并出现错误:
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:4000/masterList/", ok: false, …}
如何从我的服务 4000
获取数据并同时发布:4200
?
最佳答案
如果您的服务器托管在端口 4000 上,则需要为您的 Angular 应用指定代理,以便它将将所有 api 调用重定向到端口 4000,即使它托管在端口 4200 上。 在 package.json 旁边添加 proxy.conf.json:
{
"/": {
"target": "http://localhost:4000",
"secure": false
}
}
在MasterListService中执行以下操作:
getMasterList() {
return this
.http
.get(`/masterList`);
}
最后更改您的package.json npm启动脚本:
...
"scripts": {
...
"start": "nodemon server.js && ng serve --proxy-config proxy.conf.json",
...
}
希望有帮助。
关于javascript - 并行运行 Express 服务和 Angular 6 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54469551/