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:
Adding the following response headers:
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); });
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
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!