Having trouble transferring data using HttpClient in Angular 4 with a Symfony backend

Resolved using NelmioCorsBundle.

I am currently utilizing angular 4.3.3 for the front end and Symfony3 for the backend, with the addition of FosRestBundle.

When working with Angular, I primarily use HttpClient to handle data request and transmission.

Data retrieval works smoothly and the results are displayed without any issues. However, complications arise when attempting to transmit data as a cors error is encountered.

Remarkably, the ability to post JSON data remains intact while using postman.

The specific error message reads:

1:1 XMLHttpRequest cannot load 
http://127.0.0.1/rest/web/app_dev.php/api/comments/new/1. Response for preflight 
has invalid HTTP status code 405
Error occured.
{"content":"test comment","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="423627313602252f232b2e6c212d2f">[email protected]</a>"}

Here is the TypeScript code snippet:

    import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';

    constructor(private http: HttpClient, private globals: Globals, private activatedRoute: ActivatedRoute) {
}
    postComment(post) {
    const body = JSON.stringify(post);
    this.http.put(this.globals.baseUrl + 'comments/new/' + this.id, body).subscribe(
        res => {
            console.log(res);
        },
        err => {
            console.log('Error occured.');
            console.log(body)
        }
    );
}

In the Symfony Project: web/.htaccess

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>

Answer №1

If you want your server to respond correctly to the OPTIONS request, make sure to include the following lines in your .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

To ensure that all necessary headers are sent, use the following configuration:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "Content-Type"

The reason why handling the OPTIONS request is important is because your code is attempting a cross-origin PUT request, which prompts browsers to first send an automatic CORS preflight OPTIONS request to verify if the server allows it.

For more information, you can visit https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests. This explains the concept in detail for the specific scenario mentioned in the question.

It's worth noting that tools like Postman do not encounter this issue because they do not initiate CORS preflight OPTIONS requests like browsers do. Additionally, Postman is not restricted by cross-origin limitations that browsers impose on frontend JavaScript in web applications.

Answer №2

In the scenario where the client and server operate on separate domains, a CORS problem may arise. To resolve this issue, it is necessary to activate CORS in your server-side code. It's important to note that even if the IP addresses are identical, different ports will classify the domains as distinct entities.

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 Enforce Restricted Imports in TypeScript Project Even After Setting baseUrl and resolve Configuration

I am facing challenges enforcing restricted imports in my TypeScript project using ESLint. The configuration seems to be causing issues for me. I have configured the baseUrl in my tsconfig.json file as "src" and attempted to use modules in my ESLint setup ...

Inform the Angular2 Component regarding the creation of DOM elements that are placed outside of the

The Challenge In my Angular2 project, I am using Swiper carousel and building it with Webpack. However, Angular2 adds random attributes like _ngcontent-pmm-6 to all elements in a component. Swiper generates pagination elements dynamically, outside of Ang ...

Navigating the world of Typescript: mastering union types and handling diverse attributes

I am currently working on building a function that can accept two different types of input. type InputA = { name: string content: string color: string } type InputB = { name: string content: number } type Input = InputA | InputB As I try to impleme ...

Having trouble retrieving certain header values in Angular 4

Using Angular 4, I am making a back-end query like this: this.classzService.query({ page: this.page, size: this.itemsPerPage, sort: this.sort(), url: url }).subscribe( (res: Response) => this.onQuerySuccess(res.jso ...

The Angular 5 keyup event is being triggered twice

My app is incredibly simple, just a basic hello world. To enhance its appearance, I incorporated bootstrap for the design and ng-bootstrap for the components. Within one of my TS files, you will find the following code: showMeTheKey(event: KeyboardEvent) ...

Expired URL in Ionic 3 Navigation

I'm a novice at using Ionic. I recently started my first project about a month ago and it's nearing completion. However, I noticed that whenever I run ionic serve, my app always defaults to localhost:8100. For example, when I land on the home pa ...

Many instances of Angular subscribe being called in nested child components repeatedly

I am facing an issue with my ParentComponent that contains a *ngFor loop to dynamically add multiple instances of the ChildComponent. Each ChildComponent includes a ButtonComponent which, when clicked, updates a variable in a BehaviourSubject. In the Chil ...

How to extract a JavaScript object from an array using a specific field

When dealing with an array of objects, my goal is to choose the object that has the highest value in one of its fields. I understand how to select the value itself: Math.max.apply(Math, list.map(function (o) { return o.DisplayAQI; })) ... but I am unsur ...

Implementing ngClass change on click within an Angular component using Jasmine: A comprehensive guide

It seems like the click event is not triggering and the ngClass is not changing to active on the button I am attempting to click. -- HTML: <div class='btn-group' role='group' aria-label=""> <button type='button&apos ...

Include the providers after declaring the AppModule

When it comes to Angular 2+, providers are typically registered in the following manner: // Using the @NgModule decorator and its metadata @NgModule({ declarations: [...], imports: [...], providers: [<PROVIDERS GO HERE>], bootstrap: [...] }) ...

Angular - failure to detect function execution by spy

I've been trying to test a feature module, but I'm facing some difficulties. The last test is failing because the spy isn't detecting that the method is being called, even when I move the this.translate.use(this.currentLanguage.i18n) call ou ...

The absence of angular-cli.json is evident, as it is not hidden from

Recently starting an Angular course, I encountered an issue where my angular-cli.json file was missing. Despite researching online and checking hidden files, I still couldn't locate it. Even creating a new project didn't solve the problem. I&apo ...

Unable to retrieve information from a Node.js server using Angular 2

I am currently learning Angular 2 and attempting to retrieve data from a Node server using Angular 2 services. In my Angular component, I have a button. Upon clicking this button, the Angular service should send a request to the server and store the respo ...

Top recommendation for showcasing a numerical figure with precision to two decimal points

Within my function, I am tasked with returning a string that includes a decimal number. If the number is whole, I simply return it as is along with additional strings. However, if it's not whole, I include the number along with the string up to 2 deci ...

If an error occurs during ng lifecycle hooks, router.navigate will not function correctly

I've developed an ErrorHandler specifically for logging exceptions and then redirecting the user to a generic error page. However, a recurring problem arises when the exception occurs within a lifecycle hook or constructor method. Take for example the ...

Learning to display an error message by clicking the send button in an Angular 2 application

Despite my best efforts, I have struggled to find a solution. I have searched various websites, but everywhere they only show validations on touch or hide the button until the form is valid. How can I implement validations by simply clicking a button? Here ...

Angular with D3 - Semi-Circle Graph Color Order

Can someone assist me with setting chart colors? I am currently using d3.js in angular to create a half pie chart. I would like to divide it into 3 portions, each represented by a different color. The goal is to assign 3 specific colors to certain ranges. ...

What is the best way to retrieve the value of an input field in React when incorporating Material UI components?

I am working with a few radio input components that have been imported from material Ui react. Each radio input is wrapped in a FormControlLabel component. <FormControlLabel onClick={checkAnswerHandler} value={answer} control={<Radio color=&quo ...

Experiencing issues with Typescript typings.d.ts due to parsing error

Whenever I try to lint my TypeScript code, I encounter a parsing error: 2:3 error Parsing error: Only declares and type imports are allowed inside declare module 1 | declare module "*.json" { > 2 | var value: any; | ^ 3 | export defa ...

Angular 8 bug: Requiring 2-3 arguments, received only 1

Currently deepening my knowledge in Angular and I encountered a situation within one of my services agree(id: string) { const headers = new HttpHeaders('Content-Type: application/json'); return this.HttpClient.put(`${this.apiUrl}/agree/` ...