乐闻世界logo
搜索文章和话题

How do I send a cross-domain POST request via JavaScript?

1个答案

1

To send cross-origin POST requests in JavaScript, several approaches can be employed, including using the XMLHttpRequest object, the fetch API, or configuring CORS headers to bypass the browser's same-origin policy restrictions. Below, I will detail the implementation of each method:

1. Using XMLHttpRequest for Cross-Origin POST Requests

Although XMLHttpRequest is an older technology, it remains viable for sending cross-origin requests. For cross-origin requests to function properly, the server must include appropriate CORS (Cross-Origin Resource Sharing) headers in the response.

javascript
var xhr = new XMLHttpRequest(); xhr.open("POST", "https://api.example.com/data", true); // The third parameter `true` indicates an asynchronous request xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send(JSON.stringify({key: "value"}));

2. Sending Cross-Origin POST Requests with fetch API

The fetch API is a modern standard for network requests in browsers. It supports cross-origin requests and offers a more concise and contemporary syntax.

javascript
fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({key: 'value'}) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

3. Configuring CORS Headers

In practical server-side implementations, to successfully handle cross-origin requests, it is typically necessary to configure appropriate CORS headers on the server. For example, in Node.js, you can use the Express framework with the cors middleware to streamline this process:

javascript
const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors({ origin: 'https://your-webpage.com' // Allows cross-origin requests only from specific origins })); app.post('/data', (req, res) => { // ... res.json({ success: true }); });

Example

Suppose we need to send a POST request from a frontend JavaScript application to https://api.example.com/data, where the API supports cross-origin requests. We can achieve this using the fetch API as follows:

javascript
async function postData(url = '', data = {}) { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); return response.json(); // Parses and returns JSON data } postData('https://api.example.com/data', { key: 'value' }) .then(data => console.log(data)) .catch(error => console.error(error));

In this example, the postData function sends a POST request using fetch and waits for the response to be parsed into JSON. If the server is correctly configured with CORS headers to allow requests from the current origin, the request will complete successfully.

2024年6月29日 12:07 回复

你的答案