[英]Angular on Rails API: HTTP Request
我正在做一個教程,應該獲取要顯示的書籍列表,但是出現控制台錯誤,提示“ http:// localhost:4200 / api / books.json 404(未找到)”。
如果在瀏覽器中訪問localhost:3000 / api / books.json,則可以看到種子信息。 我的應用程序應該嘗試使用localhost:3000還是應該使用localhost:4200?
app / client / src / app / book-list / book-list-component.ts
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'app-book-list',
templateUrl: './book-list.component.html',
styleUrls: ['./book-list.component.css']
})
export class BookListComponent implements OnInit {
books: any;
constructor(private http: Http) { }
ngOnInit() {
this.http.get('/api/books.json')
.subscribe(response => this.books = response.json());
}
}
app / client / src / app / book-list / book-list-component.html
<p>
book-list works!
</p>
<ul>
<li *ngFor="let book of books">{{ book.name }}</li>
</ul>
如果需要查看設置,這是其余的代碼庫: https : //github.com/theresaluu/tut-home-library-spike
如果整個URL在另一個域上,則應指定整個URL,但是還需要在服務器上啟用CORS(有關CORS的更多信息,請參見https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS ) 。 Angular可能在另一台服務器上(我假設您以ng serve來啟動它),並且該服務器托管靜態文件+ URL重寫(如果您使用HTML5角度策略),而您使用的REST服務器在另一台服務器上港口。
應該是this.http.get('http://localhost:3000/api/books.json')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.