简体   繁体   中英

Angular on Rails API: HTTP Request

I'm doing a tutorial and I'm supposed to get a list of books to show up, but I get a console error saying " http://localhost:4200/api/books.json 404 (Not Found)".

控制台错误

If I visit localhost:3000/api/books.json in my browser, I can see the seeded info. Should my app be trying for localhost:3000 or is it supposed to be using 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>

Here is the rest of the code base in case you need to look at the setup: https://github.com/theresaluu/tut-home-library-spike

You should specify the whole URL if its on another domain, but also you need to have CORS enabled on the server (more on CORS here https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS ). Angular is probably on another server (I assume you start it with ng serve), and that server is hosting the static files + URL rewrite (if you are using the HTML5 angular strategy) and the REST server that you are consuming is on a different port.

It should be this.http.get('http://localhost:3000/api/books.json')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM