404 error occurs when making an Angular 7 http post request to a PHP script

I recently created a contact form for my Angular 7 website, which sends a JSON object to a PHP file.

Here is a screenshot of the console error message

Although the POST request is working, I am receiving a 404 error. The MessageService is passing the absolute path to the PHP file along with the message object. Here is a snippet from the message.service.ts file:

export class MessageService {
  baseUrl = '<domain>/dev/src/app/entities/contact/message.php';

  constructor(private http: HttpClient) { }

  send(message: Message) {
    this.http.post(this.baseUrl, { data: message }).subscribe((data) => {
      console.log('Sent Data', data);
    }, (error) => {
      console.log('Something went wrong', error);
    });
  }
}

Here is the content of the message.php file:

<?php
  header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
  header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
  header('Access-Control-Max-Age: 1000');
  header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

  $post = file_get_contents('php://input');

  echo $postdata;
?>

Both the MessageService and message.php are located in the same folder. However, I am uncertain if the absolute path specified in the POST request is correct.

You can view the file tree by clicking here

I would greatly appreciate any assistance in resolving this issue.

Thank you in advance

Sascha

Answer №1

Consider utilizing the code snippet below to allow access control:

header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_REFERER']);

It is recommended to use the HTTP_REFERER instead of HTTP_ORIGIN as some browsers do not set HTTP_ORIGIN and it can pose security risks.

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

Exporting files to the www folder during Ionic 5 build process

I have a project in progress for developing an application that will cater to multiple companies. Each company would require its own customized app with unique environment variables. To achieve this, I have created "env.js" files specific to each company, ...

Error message: Unable to locate provider for @Attribute('sampleString')

We are currently working on writing unit tests for a component that utilizes a third-party JavaScript library. The constructor of our component is structured as follows: @Constructor(@Inject(ElementRef) private eleref: ElementRef, @Attribute('sampleS ...

Generate dynamic rows with auto-generated IDs on click event in Angular

Can anyone assist me in dynamically adding rows and automatically generating IDs? I am currently using a click event for this task, but when adding a row, I have to input details manually. Is there a way to automate this process? Any help would be greatly ...

The real-time updates on an Angular 2 website can be seen across multiple devices simultaneously

Just getting started with Angular 2 and ran into an interesting issue. When setting up my website, NPM defaults the server to http://localhost:3000. To test the site on another computer, I tried accessing it using my IP address http://10.x.x.x:3000 and eve ...

What is the best way to execute operations on two distinct datasets within a single function using RxJS?

Is there a way to perform operations on two separate data collections within a single function in RxJS, returning an observable instead of void? This function is located within a service and I intend to subscribe to it from my component. I believe some re ...

The canActivate function must be responsive to the true or false value of this.authService.isLoggedIn before proceeding

I am facing a problem with my app's routing functionality. When the user logs in with their Google email, I want the app to route to the home page: "". Everything seems to work fine except for the canActivate routeGuard. During the AuthLogin ...

Rounding Decimals using JavaScript

I am facing the challenge described in this particular query. In most cases, my code works fine to round numbers to two decimal places with the following formula: Math.round(num * 100) / 100 However, there was a peculiar scenario where it failed. When tr ...

Should I call `complete()` on the takeUntil Subject within the ngOnDestroy method?

To prevent memory leaks caused by Observables inside Components, I always use the takeUntil() operator before subscribing. Here is an example of how I implement it in my components: private stop$ = new Subject(); ngOnInit(): void { this.http .get( ...

gyp ERROR: Npm encounters difficulty in obtaining a local issuer certificate

I recently did a fresh installation of Windows 10, keeping it clean except for adding cygwin to access Unix commands in the command prompt. During my attempt to install @angular/cli with the command npm install -g @angular/cli, I encountered an error afte ...

Collaborating on a project that has been developed using various editions of Typescript

Currently, I am part of a team working on a large project using Typescript in Visual Studio. As we have progressed through different versions of the project, we have encountered an issue with versioning the installed TypeScript within Visual Studio. Situa ...

Contrasting importing a module in app.module versus a component

Angular 5 Can you explain the distinction between importing a module in app.module versus importing it directly into the component where it is needed? In particular, why is it necessary for a module to be included in node modules, app.module, the import ...

Tips on selecting an element with matching element attributes on a button that contains a span tag using Protractor in TypeScript

https://i.sstatic.net/LAhi8.jpg Seeking assistance with creating a protractor TypeScript code to click a button with _ngcontent and span class. Does anyone have any suggestions on how to achieve this? Here is the code snippet from the site: <form _ngc ...

Issue with displaying options in Angular2 v2.4.9 HTML select element

Ever since I made the transition from AngularJS to Angular2, I've been facing a peculiar issue. The select element's options data is fetched from a Solr query, which always returns a 200 response with the data in a timely manner. However, the pr ...

Why is my RxJS timer not waiting for the specified time?

I'm diving into the world of RxJS and trying to grasp its concepts. During some testing, I encountered a puzzling issue that has me stumped. Below is the snippet in question : let item = { id: 1, name: 'chair' }; const asyncItem = timer(20 ...

Deliver the object to the styled component in Material UI

I have a styled component: import {styled} from '@mui/material/styles'; export const MovieModalStyle = styled(Box)(({theme}) => ({ // ... background: `url(${'https://image.tmdb.org/t/p/w780/' + movie.backdrop_path})`, })); Look ...

Retrieve the ngModel's current value

One of the challenges I encountered is with a textarea and checkbox interaction. Specifically, once the checkbox is checked, I aim to have the value appear in the textarea. <div class="message-container"> <textarea *ngIf="mode === 1" ...

I'm having trouble with one of my filter pipes not displaying any results. Can anyone help me troub

I have recently included a new filter for DL, but it seems that the results are not showing up as expected. Any ideas on what changes I should implement? <div class="form-group float-left mr-4"> <strong>DL</strong> <br /> ...

Adding an element within an ngFor iteration loop

I'm currently working on a code snippet that displays items in a list format: <ul> <li *ngFor="#item of items">{{item}}</li> </ul> These items are fetched from an API through an HTTP call. Here's the code snippet for tha ...

Error message: Angular 2 JsonpModule import not defined

Within my app.module.ts file, I have the specified code import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {JsonpModule} from '@angular/http'; import {AppComponent} from & ...

What could be the reason for my Form styling failure?

Currently working on freecodecamp's portfolio creation exercise. It should be a straightforward task, but I'm facing a small issue that's puzzling me. I'm trying to remove the border and outline (when focused) from my contact-area form ...