Home > Web Front-end > JS Tutorial > How Can I Make Cross-Domain POST Requests in JavaScript using CORS?

How Can I Make Cross-Domain POST Requests in JavaScript using CORS?

Mary-Kate Olsen
Release: 2024-12-16 20:01:10
Original
748 people have browsed it

How Can I Make Cross-Domain POST Requests in JavaScript using CORS?

Sending Cross-Domain POST Requests via JavaScript

Cross-domain requests are a common challenge in web development. In JavaScript, there are several ways to send a cross-domain POST request, but one of the most straightforward methods involves leveraging the "Cross-Origin Resource Sharing" (CORS) standard.

CORS Configuration on the Server

Enable CORS on the server that will receive the POST request by:

  1. Adding the following response headers:

    • Access-Control-Allow-Origin: from.com (replace from.com with the origin of the request)
    • Access-Control-Allow-Methods: POST
    • Access-Control-Max-Age: 1000
    • Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With

Cross-Domain POST via JavaScript

In JavaScript, you can use the fetch API to send a cross-domain POST request:

fetch('https://to.com/postHere.php', {
  method: 'POST',
  mode: 'cors',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ some: 'json' })
})
  .then(response => response.json())
  .then(responseData => {
    console.log(responseData.someKey);
  })
  .catch(error => {
    console.error('POST failed', error);
  });
Copy after login

This code makes a POST request to https://to.com/postHere.php from a different origin (from.com). It sets the necessary headers for CORS and stringifies the request body as JSON.

Handling OPTIONS Requests

When a client sends a cross-domain POST request, the browser first sends an OPTIONS request to the server to check if the server supports the request. The server should respond to this request with the appropriate CORS headers to indicate that the POST request is allowed.

Considerations

  • This method requires CORS support on the server.
  • The request will make two requests to the server: an OPTIONS request followed by the POST request.
  • CORS may not work on all devices, particularly mobile devices.

The above is the detailed content of How Can I Make Cross-Domain POST Requests in JavaScript using CORS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template