Can PHP Webpage Make an AJAX POST Request to Express Server on the Same or Different Ports?

Trying to enable a POST request through AJAX from a site to an express server triggered some unexpected challenges. When running the server on the same localhost port as the website (localhost:8080), the webpage fails to render and an error message pops up saying, "Cannot GET /mogle/income.php." This is happening despite the fact that "mogle/income.php" is intended to be the page for the request. Conversely, when changing the server to a different port (e.g., localhost:8000), the AJAX POST call stops functioning altogether. The common belief appears to be that requests across different ports can only be done with JSONP, which exclusively supports GET requests, while my requirement demands the use of POST.

In an attempt to rectify the issue with the webpage failing to render on the same port scenario, I implemented an app.get function in my server.js file, outlined below. However, this resulted in the PHP file being downloaded instead of rendering as expected, likely due to its file type difference compared to HTML files. As a result, there arises a concern about having to implement individual app.get statements for every other webpage present on the site (e.g., homepage.php, login.php) within the server.js file.

app.get("/mogle/income.php", (req, res) => {
  // Using "../../" due to server file location
  res.sendFile(path.join(__dirname, "../../income.php"));
});

app.post("/path", async (req, res) => {
  // Handle response
});

Reflecting on the constraints and issues faced, it beckons the question - what is the standard practice for transmitting requests (both POST and GET) from websites to servers regarding port configurations?

Answer №1

Consider the following solution:

  • To allow POST/GET/PUT requests on your server, update the header values as shown below:

    const express = require('express')
    const bodyParser = require('body-parser');
    const app = express()
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}) );
    
    app.all("/*", function(req, res, next){
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
      res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
      next();
    });
    
    app.post('/yourendpoint', function (req, res) {
      res.send(req.body)
    })
    
    app.listen(8080, function () {
      console.log('Server Listening on - localhost:8080!')
    })
    

For Angular Example, here is how you can post data from client side:

let myDataObj = { name: "test", age: 22 , otherprop: "my post data values"};
this.http.post('http://localhost:8080/yourendpoint', JSON.stringify(myDataObj), {
  headers: headers
})
.subscribe(data => {
  console.log(data);
});

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

What is the best way to show toast notifications for various selections in a dropdown menu?

I have a dropdown menu labeled "FavoriteFoods" that includes options such as "Pizza," "Sushi," "Burgers," and "Biryani." When one of these food choices is selected from the dropdown, I would like a toast pop-up to appear with the message "Great choice!" ...

Regain the cursor focus on a text input field once it has been disabled and re-enabled using AngularJS

In my code, I have implemented an input field along with a $watch function that triggers a server request when the scope variable changes. While the server request is being processed, I disable the input field. However, once the request is complete and the ...

Is there a way to compare timestamps in PostgreSQL using moment.js and focus only on the date aspect?

I've encountered a small issue that has me stumped - I'm trying to figure out the best solution for it. The problem lies in a table I have, with attributes named "Start" and "End". My objective is to store every row in an array where the "Start" ...

Prevent form submission using jQuery based on ajax response, or allow it to submit otherwise

After setting up some jQuery code to handle form submission, the functionality is working well when certain conditions are met. However, I am facing a challenge in allowing the form to be submitted if the response received does not match specific criteria. ...

"Populate a div with an array of images extracted from a JSON file

I found a website that provides an array of images like the sample below. { "imageUrl":"http://server06.amobee.com/aspx/nadav/test/banner320x50.png", "expandedImageUrl":"http://server06.amobee.com/aspx/nadav/test/banner320x320.jpg" } My ob ...

Unlocking the secret to obtaining durable identity provider tokens for JavaScript in web browsers

Currently, I am working on implementing browser-side JavaScript code for login with Facebook, Amazon, Twitter, and Google using Cognito. I have reached a point where I am able to obtain client tokens for all four platforms. However, the issue is that thes ...

Adding a panel dynamically with Bootstrap incorrectly

I have been using the Collapse panel in Bootstrap and it was working perfectly when implemented statically. However, I encountered an issue when trying to add it dynamically. HTML <form> <div class="form-group" > <label for="c ...

Angular: Exploring the possibilities of condition-based click event implementation

In my component, there are two elements: 'order information' and a 'datepicker'. When clicking on the component, it will display the order information. However, I want to prevent the click event from being triggered if the user clicks ...

Tips for comparing props in the ComponentDidUpdate method when dealing with a complex data structure that is connected to Redux

I have been experimenting with the new lifecycles of React v16. It works perfectly fine when comparing single keys. However, when dealing with large data structures like Arrays of objects, performing deep comparison can be quite expensive. My specific sce ...

Using for loops in Vue.js to dynamically generate HTML elements

I have a JSON object passed into an EJS template, and I want to achieve the same table structure in VUE.js. However, it seems like v-for in Vue only works with li tags. Is there a way to create a similar loop in VUE that generates HTML elements like show ...

Guide to displaying a server response within a React application

Is there a way for me to synchronize the data retrieved from the server with the template in my component? I am trying to fetch data from the server, perform some parsing, and then display it in a table within the component. However, the issue is that the ...

PHP code for sending email with attachment file

I have created an HTML form with the option to upload a file and send it to me via email. Additionally, I already have a PHP script that sends textbox values and text area values via email. Now, I would like the uploaded file from the form to be sent to m ...

Execute function when button is not active

Within my Angular 2 application, I have a form along with the following code snippet that relates to the button responsible for submitting the form. <button (mouseover)="showMesageValidation()" class="edm-button" type="submit" [disabled]="!f.valid"> ...

Using React js to transform objects into arrays for useState

Hey there! I'm currently working on a webshop demo project for my portfolio. I've encountered an issue while trying to fetch data from commerce.js. The data is in the form of objects, which are causing problems when I try to map them. I've a ...

When the CSS animation has finished in JavaScript

I am currently developing a game using HTML/JavaScript, and I have implemented a "special ability" that can only be activated once every x seconds. To indicate when this ability is available for use, I have created a graphical user interface element. Since ...

Is it possible to interpret the camera using radius or diameter instead of the traditional x, y, z coordinates

I've been exploring this scenario where I am trying to figure out if it is possible to move a camera by adjusting the radius and diameter instead of using x, y, z positions (Vectors). Currently, I am working with a cube, but my goal is to introduce a ...

Ways to verify if a firebase timestamp surpasses the present date

Would you help me with comparing a timestamp field with the current date using JavaScript? This is what I have tried so far: // Initialize an empty array to store documents let myDocs = []; // Call the getDocs function and handle the response await getDo ...

Modify a class attribute within a function

I need to modify the this.bar property within my class when a click event occurs. The issue is that the context of this inside the click function is different from the this of the class. export class Chart { constructor() { this.bar; } showC ...

Experiencing difficulties when trying to set up the express/body-parser node js eclipse

I'm currently working my way through the instructions for setting up express web servers using the eclipse/node js plugin in a tutorial book, and I am struggling to install express or create the necessary subfolders as instructed. Despite following th ...

Advantages of passing individual variables instead of the entire object from HTML to JavaScript in AngularJS

When it comes to passing the iterating object from HTML to Javascript, there are two approaches that can be taken. The first approach involves passing the iterating object as a whole, while the second approach only passes the required properties of the obj ...