[英]C'ant post send post to api route using Angular http
我正在嘗試使用Angular5在Laravel API路由的URL中的POST上發送值。 但是,當我發送請求時,我的瀏覽器控制台沒有任何錯誤,但是沒有記錄任何網絡活動。 這很奇怪,因為我可以在控制台中打印路由,並且與我的API中的路由完全相同。 我的路線具有100%的功能,因為它可以在Postman中使用。 請幫忙...
這是我的收藏夾
<button (click)="addFavorite(stationId)">Add to favorite</button>
這是我的最愛.component.ts
@Component({
selector: 'add-favorite',
templateUrl: './favorite.component.html',
styleUrls: ['./favorite.component.css']
})
export class FavoriteComponent implements OnInit {
@Input() stationId: number;
constructor(
private favoritesService: FavoritesService,
private route: ActivatedRoute,
private router: Router
) {
this.route.params.subscribe( params => this.params = params);
}
observable: Observable<number>;
params: Params;
/*this.params['id']*/
ngOnInit() {
}
addFavorite() {
this.favoritesService.postFavorite(this.stationId);
}
}
這是我最喜歡的服務
@Injectable()
export class FavoritesService {
private apiUrl = environment.apiUrl;
private user_id = 2;
constructor(private http: HttpClient) { }
postFavorite(stationId: number): Observable<number> {
const url = `${this.apiUrl}/user/${this.user_id}/favorites/${stationId}`;
console.log(url);
return this.http.post<number>(url, {station_id: stationId});
}
}
這是我的Laravel API路線:
Route::post('user/{user_id}/favorites/{station_id}', 'FavoriteController@store');
確保在請求中傳遞CSRF令牌 。
理想情況下,您將編寫一個攔截器以自動注入CSRF令牌,但是對於該特定請求,您可以執行以下操作:
在Blade布局的<head>
部分中:
<meta property="csrf-token" name="csrf-token" content="{{ csrf_token() }}">
這會將您請求的相應CSRF令牌放置在腳本的可訪問位置。 我建議您通過在根組件中添加參數來傳遞值。
postFavorite(stationId: number): Observable<number> { const url = `${this.apiUrl}/user/${this.user_id}/favorites/${stationId}`; console.log(url); let token = document.querySelector('meta[property="csrf-token"]')['content']; return this.http.post<number>(url, {station_id: stationId}, { headers: new HttpHeaders({ 'X-CSRF-TOKEN': 'application/json', }) }); }
這會將CSRF令牌從<head>
標記添加到適當的標頭中,並與您的請求一起發送。
您可以在以下Laravel中找到有關CSRF令牌的更多信息: Laravel-CSRF保護
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.