Having trouble sending posts to an API route with Angular's HTTP module

When attempting to send values via a POST request in the URL of an Angular5 Laravel API route, I encountered an issue. Despite not receiving any errors in the browser console, no network activity was recorded upon sending the request. It is perplexing as I can verify that my route matches the one on my API by printing it in the console. The route functions perfectly when tested with Postman. Any assistance would be greatly appreciated...

Below is the code snippet from my favorite.html file:

<button (click)="addFavorite(stationId)">Add to favorite</button>

This is the excerpt from my favorite.component.ts file:

@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);
 }
}

This is the segment from my favorite service:

@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});
 }
}

Check out my console output here

Lastly, here is the Laravel API route in question:

Route::post('user/{user_id}/favorites/{station_id}', 'FavoriteController@store');

Answer №1

Ensure that the CSRF token is included in your request.

It's a good practice to create an interceptor to automatically add the CSRF token, but for this particular request, you can manually inject it as follows:

  • In the <head> section of your Blade layout:

    <meta property="csrf-token" name="csrf-token" content="{{ csrf_token() }}">
    

This will make the CSRF token easily accessible for your script by including it as a meta tag value. Consider passing this value as a parameter to your root component instead.

  • In your Favorite service:
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',
        })
   });
}

This code snippet retrieves the CSRF token from the <head> section and includes it in the header of your request.

To learn more about CSRF tokens in Laravel, visit: Laravel - CSRF Protection

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to Transform XML into a Text Input within a C# SOAP Web Service Function

Recently, I was tasked with developing a C# SOAP Webservice that is capable of converting data from JSON to XML and vice versa. So far, I have successfully implemented the service along with two methods. The conversion method from JSON to XML is functionin ...

What steps can be taken to resolve the error message "JSON parse error - Extra data: line 8 column 3 (char 153)" in the Django Rest Framework?

When trying to create a new post with the following code: { "Number": 1, "name": "1005001697316642", "image": "https://", "description": "fffffffff", "price": & ...

The formBuilder validator pattern seems to be malfunctioning

I am attempting to display a message when the password does not meet the formGroup pattern. Here is how my FormGroup is initialized: this.signupForm = fb.group({ userName: ['', Validators.compose([Validators.required,Validators.pattern(/^&bsol ...

Showing hierarchical objects retrieved from JSON response

I'm still learning React, so bear with me if this is a simple issue. I have some nested data that I want to show in a list format. The data is fetched and displayed below: data: [ { "id": 1, "domain_url": "localhost", "created_on": "2020-05-26" ...

Issue with Jest: receiving error message "Module cannot be found" despite having the package installed

Recently, I went through a cleanup and update process for a private package to make it compatible with Vite. Initially, the package.json file had the following structure: { "name": "@myRegistry/my-package", "version": &qu ...

Is the Angular maxlength parameter causing issues with user input?

Previously, the old ng-maxlength="5" would trigger a field error but allow user input to continue. Now, with maxlength="5", it seems that input is being prevented altogether. I have novalidate on my form - could Angular be causing this? Should input be all ...

Issue: StaticInjectorError(DynamicTestModule)[CityService -> Http]: Http provider not found

I am working on a service that retrieves all cities from a web service. @Injectable() export class CityService { constructor(private http: Http, private router: Router, private auth: AuthService) { } public getAllCity(): Observable<City[]> { ...

Ensuring external library object properties are limited in Typescript

Trying to utilize the notify function from an external library has been a bit challenging. The declaration in the library is as follows: // library.js export declare const notify: { (args: NotificationsOptions | string): void; close(id: unknown): ...

Using TypeScript with Styled Components .attrs

I'm a bit perplexed about using the .attrs() function in conjunction with TypeScript. Let's consider the code snippet below: BottleBar.tsx: interface IBottleComponentProps { fill?: boolean } const BottleComponent = styled.div.attrs<IBottl ...

In Angular/Bootstrap, what does displaying "onChange started" and "onChange completed" in the console signify?

Recently, I incorporated a select element into an Angular component. Upon loading the component in the browser and selecting a value from the list, I noticed these specific messages appearing in the console: onChange started onChange completed I find it p ...

The subscription function in observables may result in values that are undefined

I integrated a new angular 2 library into my application called "angular2-grid". This library is located within the node_modules folder. Furthermore, I created a service as shown below: import { Injectable } from '@angular/core'; import { Htt ...

Turning a group of objects into a JSON format

In my current setup, I have a RESTful web service utilizing Spring, Hibernate, c3p0, and Sybase, all running on Tomcat. This service functions as a search engine, returning a collection of objects based on specific search criteria. These objects have a com ...

Exploring the root domain in PHP on your hosting provider's cPanel

Currently, I am using this code on my local server if (isset($_FILES['image'])) { if(isset($_POST['directory'])){ $directory = $app->request->post('directory'); $ ...

The pathway specified is untraceable by the gulp system

Hey there, I've encountered an issue with my project that uses gulp. The gulpfile.js suddenly stopped working without any changes made to it. The output I'm getting is: cmd.exe /c gulp --tasks-simple The system cannot find the path specified. ...

Nearly at the finish line with long polling using PHP and AJAX!

Currently, I am immersed in a school project that involves Arduino boxes sending sensor data to a MySQL database, with a website set up to display this information. The sensor data is transmitted approximately every 6 seconds. While I don't possess e ...

The Angular filter feature operates on individual columns instead of filtering all columns simultaneously

Introduction I am currently working on implementing a feature in my Angular application where the column filter continuously updates the results based on the selected filters. The issue I'm facing is that when I select a filter in one column, it corr ...

What is the best approach for managing a One-to-One JSON loop?

My application features a class called "User" with an attribute that points to another user. The issue I'm facing is that one user has another user as their attribute, creating a loop. This situation differs from the typical scenario where one class h ...

The art of expanding Angular's HTTP client functionality

I understand that the following code is not valid in Angular, but I am using it for visual demonstration purposes. My goal is to enhance the Angular HTTP client by adding custom headers. I envision creating a class like this, where I extend the Angular h ...

Establish a connection using Angular 4 HTTP POST to communicate with a Java REST API, as it is not permitted on the server

I am facing an issue with my Angular 4 client service that is calling a REST method declared on a Java server using a PostMapping annotation. When I make the call from Angular, it is not accepted by the server. However, when testing it on Postman, it work ...

Load nodes for jsTree based on the results of a query when requested by the user

I've been researching extensively, but I have yet to discover the correct solution. I am interested in learning how to dynamically generate a jsTree where the nodes are loaded from a database. The data will be retrieved by a function. My objective i ...