当我导入HttpClient调用我自己编写的 node.js API 时,URL 的设置存在一些问题。
例如:
import { HttpClient, HttpHeaders } from '@angular/common/http';
export class myComponent implements OnInit {
constructor(
private http: HttpClient,
) {}
ngOnInit(): void {
this.http.get('http://127.0.0.1:3000/getData/theme').subscribe(data => {
});
});
}
//angular default port 4200,
//node.js default port 3000,
Run Code Online (Sandbox Code Playgroud)
当我设置this.http.get('/getData/theme')了get将呼叫http://127.0.0.1:4200,这是错误的。如果我this.http.get('http://127.0.0.1:3000/getData/theme')为本地开发设置它的工作原理。但是,当ng build设置到实际服务器时,它无法正常连接。
控制台:
GET http://127.0.0.1:3000/getData/theme
net::ERR_CONNECTION_REFUSED
GET http://localhost:3000/structureData/themeData
net::ERR_CONNECTION_REFUSED
Run Code Online (Sandbox Code Playgroud)
如何设置正确的 URL 以使其同时满足在线和本地开发状态?
angular-cli 服务器 - 如何将 API 请求代理到另一台服务器?
我设置了 package.json:
"start": "ng serve --proxy-config proxy.conf.json"
Run Code Online (Sandbox Code Playgroud)
和 …
因此,我尝试使用http: HttpClientfrom将来自 REST 源的数据加载到我的 Angular 6 应用程序中'@angular/common/http'。使用ng serve --open虽然在浏览器中调用应用程序并不能完成这项工作。我认为 CORS 是这里的问题。我想我要么必须设置服务器或客户端标头Access-Control-Allow-Origin或其他东西,但我已经尝试了多种方法,但没有成功使这个简单的 REST 调用工作。所以下面是我编码的内容。
在浏览器中调用 Angular 应用会响应以下错误:
Failed to load http://localhost:8080/mysite-backend/rest/report/single/d83badf3:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access.
Run Code Online (Sandbox Code Playgroud)
http://localhost:8080/mysite-backend/rest/report/single/d83badf3不过,在 Chrome 浏览器中调用相同的 URL ( ) 效果很好:
{"id":"d83badf3","language":"en","categoryId":"a5","title":"Simcity","created":1527723183880,"modified":1527723183880}
Run Code Online (Sandbox Code Playgroud)
在 Angular 6 中,我使用了以下由ng generate service tour. 在其中,我创建了一个方法getTour(id: string),它只在 URL 上调用 REST,并将检索到的 JSON 字符串作为 …