javascript - 对 Play REST 服务器的 Angular 2 http 请求

标签 javascript json http angular playframework

我正在实现 Angular 2 服务,该服务通过 http 请求从 Play Framework 服务器获取 JSON 数据。

http://localhost:9000/read返回 JSON 数据,如 [{"id":1,"name":"name1"},{"id":2,"name":"name2"}]

这是我的 Angular 服务代码(来自本教程 https://angular.io/docs/ts/latest/guide/server-communication.html):

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Hero }           from './hero';
import { Observable }     from 'rxjs/Observable';
@Injectable()
export class HttpService {
private heroesUrl = "http:localhost:9000/read";  // URL to web API
constructor (private http: Http) {}
getHeroes (): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
                .map(this.extractData)
                .catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
  const body = error.json() || '';
  const err = body.error || JSON.stringify(body);
  errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
  errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}

但是浏览器中的请求是这样的:

GET XHR http://localhost:4200/localhost:9000/read [HTTP/1.1 404 Not Found 5ms]

因此,当需要绝对 URL 时,Angular 会创建相对 URL。 我也可以...

1)在代码中修复它。

2)或者让 Angular 2 和 Play 在同一个端口上运行。

3)使用 JSONP 或其他东西。

最佳答案

你的相对 url 的原因仅仅是因为你有一个错字,这导致了这个。而不是

private heroesUrl = "http:localhost:9000/read";

应该是

private heroesUrl = "http://localhost:9000/read";

这里可能不需要其他魔法。您可能会遇到 cors 问题。但由于这是一个 Playground ,而不是实际的开发,所以在 CORS 的情况下,您可以在 chrome 中轻松启用 CORS。但这自然不推荐在现实生活中的应用程序中使用。但对于玩耍来说,这就足够了。

关于javascript - 对 Play REST 服务器的 Angular 2 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41728314/

相关文章:

javascript - 在 react 中使用过多的 useState 钩子(Hook)。我该如何重构这个?

php - 使用 jQuery 自动 PHP 通知

javascript - jQuery 为选项卡使用特定的 UL 元素

json - 如何从 Go http.Request 中检索对象?

javascript - Webpack 和 AWS Lambda 问题 - 模块上缺少处理程序

javascript - 我如何访问这个 json 中的内容?

php - 使用 jquery 从 PHP/MySQL 查询中获取 JSON 数据到 html 标签中

javascript - 根据数组值 angularjs 分配 ng-class 值

api - RESTful API 设计 : PUT or POST for creating many-to-many relationships?

javascript - Uncaught Error : [$injector:unpr] Unknown provider: dependency1Provider <- dependency1 <- $http <- $compile