AMP应用能否发送Content-Type: application/json的POST请求?
application/json POST Requests with AMP Forms Great question! The amp-form component has a key limitation here: by default, it only supports multipart/form-data or application/x-www-form-urlencoded as request content types, and there’s no direct way to set it to application/json using standard amp-form attributes. But don’t worry—there are two reliable workarounds to get this done:
Option 1: Use amp-script to Manually Construct JSON Requests
AMP’s amp-script component lets you run custom JavaScript (within AMP’s security constraints) to handle form submission, construct a JSON payload, and send it with the correct headers.
Step 1: Add the amp-script Component
First, include the amp-script script in your page’s <head>:
<script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>
Step 2: Build Your Form and Script
Create your form, then use amp-script to listen for the submit event, collect form data, and send the JSON request:
<!-- Your form --> <form id="json-submit-form" method="post"> <input type="text" name="fullName" placeholder="Full Name" required> <input type="email" name="emailAddress" placeholder="Email" required> <textarea name="message" placeholder="Your Message" required></textarea> <button type="submit">Send</button> </form> <!-- AMP Script to handle submission --> <amp-script layout="container" src="https://your-domain.com/form-submit.js"> <div fallback> Submission requires JavaScript enabled. </div> </amp-script>
Step 3: Write the Submission Logic
In your external form-submit.js file (must be served over HTTPS and allowed by AMP’s CORS rules), add this code:
const form = document.getElementById('json-submit-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); // Collect form data and convert to a JSON object const formData = new FormData(form); const jsonPayload = Object.fromEntries(formData.entries()); try { const response = await fetch('https://your-api-endpoint.com/submit', { method: 'POST', headers: { 'Content-Type': 'application/json', 'AMP-Same-Origin': 'true' // Required for AMP XHR requests }, body: JSON.stringify(jsonPayload), credentials: 'include' // Include if your API requires cookies }); if (response.ok) { // Handle success (e.g., show a message) alert('Form submitted successfully!'); form.reset(); } else { // Handle errors from the API const errorData = await response.json(); alert(`Submission failed: ${errorData.message}`); } } catch (error) { // Handle network errors console.error('Request error:', error); alert('Network error—please try again later.'); } });
Note: If you prefer inline script (max 15KB), you can use the script attribute on amp-script instead of linking to an external file.
Option 2: Use a Server-Side Proxy
If you don’t want to use custom JavaScript, set up a simple proxy server to receive the multipart/form-data request from amp-form, convert it to JSON, and forward it to your target API.
Example Proxy with Node.js/Express
Here’s a quick example using Express and Multer to parse form data:
const express = require('express'); const multer = require('multer'); const fetch = require('node-fetch'); const app = express(); // Configure Multer to parse multipart form data const upload = multer(); // Proxy endpoint app.post('/amp-form-proxy', upload.none(), async (req, res) => { // Convert form data to JSON const jsonPayload = req.body; try { // Forward request to your API const apiResponse = await fetch('https://your-target-api.com/submit', { method: 'POST', headers: { 'Content-Type': 'application/json', // Add any other headers your API requires }, body: JSON.stringify(jsonPayload) }); // Pass the API response back to AMP const responseData = await apiResponse.json(); res.status(apiResponse.status).json(responseData); } catch (error) { console.error('Proxy error:', error); res.status(500).json({ error: 'Failed to forward request' }); } }); app.listen(3000, () => console.log('Proxy server running on port 3000'));
Update Your AMP Form
Point your amp-form’s action-xhr to the proxy endpoint, and use standard AMP form success/error states:
<form method="post" action-xhr="https://your-proxy-server.com/amp-form-proxy" target="_top"> <input type="text" name="fullName" placeholder="Full Name" required> <input type="email" name="emailAddress" placeholder="Email" required> <textarea name="message" placeholder="Your Message" required></textarea> <button type="submit">Send</button> <!-- Success state --> <div submit-success> <template type="amp-mustache"> ✅ Form submitted successfully! </template> </div> <!-- Error state --> <div submit-error> <template type="amp-mustache"> ❌ Submission failed: {{error}} </template> </div> </form>
Key Takeaway
amp-form doesn’t natively support application/json requests due to AMP’s security and compatibility constraints, but either of these methods will let you send JSON payloads to your API while staying compliant with AMP rules.
内容的提问来源于stack exchange,提问作者ghashi

