Web Front-end
JS Tutorial
How to send a POST request using Fetch in JavaScript? (API Integration)
How to send a POST request using Fetch in JavaScript? (API Integration)
The main reason why fetch POST body does not work is that the Content-Type is not set or the body format does not match: JSON requires headers to be set to 'application/json' and the body to use JSON.stringify(); form data uses URLSearchParams; FormData does not set Content-Type manually.

When fetch() sends a POST request, the body does not take effect?
The most common reason is that Content-Type request header is not set, or body format does not match the backend expectation. The browser will not automatically complete the request header for you, nor will it convert the object into a JSON string.
-
headers: { 'Content-Type': 'application/json' }, otherwise the backend may not receivebodyor the parsing may fail. -
bodymust be a string (such asJSON.stringify({name: 'Alice'})), and objects cannot be passed directly - If the backend requires form data (
application/x-www-form-urlencoded), you must usenew URLSearchParams({name: 'Alice'})to constructbody - Note:
fetch()does not have cookies by default. When crossing domains, you need to addcredentials: 'include'to send credentials.
POST is successful but the backend cannot receive the parameters? Check these points
The phenomenon is usually a response status code of 200, but req.body in the backend log is an empty object or undefined - this is almost always a front-end serialization or request header issue.
- In the Node.js Express scenario, confirm that the backend has
app.use(express.json())and/orapp.use(express.urlencoded({ extended: true })) - The front-end passes
application/json, but the back-end is only equipped withurlencodedmiddleware → Baifa - When using
FormDatato pass files or mixed fields on the front end, don’t setContent-Typeheader and let the browser automatically generate the boundary (manually setting it will destroy the format) - Use
curl -vor the Network panel of the browser DevTools to see the actual request headers and raw bodies, which is much more reliable than guessing.
fetch POST reports TypeError: Failed to fetch?
This error name is misleading. It does not necessarily indicate a network failure, but more likely CORS, HTTPS mixed content, or the request was intercepted by the browser.
- Non-2xx status codes (such as 401, 500) will not trigger
catch, but will go throughthen. You must manually checkresponse.okorresponse.status - CORS errors usually display "No 'Access-Control-Allow-Origin' header" on the console. At this time, the problem is configured on the server side. Adding
mode: 'cors'on the front end is useless. - Requests initiated under the local file protocol (
file://) will be directly rejected by the browser and must be run on a local service (such ashttp://localhost) - If the backend returns HTML (such as a login jump page) but the frontend parses it as JSON,
response.json()will throw a syntax error, which looks like a fetch failure.
Should I use async/await? How to avoid .catch swallowing errors
It is more intuitive to use async/await , but don't forget that the successful response fetch() may also be a business error (such as 400 with error message), which cannot be caught purely by try/catch .
- Recommended structure:
const res = await fetch(url, options); if (!res.ok) throw new Error(`${res.status} ${res.statusText}`); return res.json(); - Don't write
fetch().then(...).catch(err => console.error(err))- this will swallow all subsequent errors in the chain, including.json()failures - If you need to unify error handling, encapsulate a layer of functions, do status judgment and JSON parsing, and then throw contextual errors (for example, including
urlandbody) - Note:
awaitonly waits for promise to settle and does not guarantee business success; network timeout needs to be controlled byAbortController
The real trouble is never how to send POST, but that the back-end interface document does not clearly state the expected Content-Type, field nesting level, whether an authentication header is required, or even quietly changes the path - capture the packet first when encountering a problem, don't rush to change the front-end logic.
The above is the detailed content of How to send a POST request using Fetch in JavaScript? (API Integration). For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20606
7
13699
4
Correct way to dynamically access form control values in Angular
Apr 16, 2026 am 08:42 AM
In Angular, if you need to dynamically obtain the value of a specified control in the FormGroup through function parameters, you should use square bracket syntax (controls[gotInput]) instead of dot syntax (controls.gotInput). Otherwise, an error will be reported because the property name is treated as a literal instead of a variable.
How to create scheduled events in Discord.js
Apr 21, 2026 am 04:09 AM
This tutorial details how to create Discord scheduled events using the discord.js library. We'll address a common TypeError when initializing GuildScheduledEventManager, explaining that its root cause is that the constructor expects a Guild object rather than a guild ID string. By obtaining the correct Guild object and passing it to the manager, developers can successfully create and manage scheduled activities for the server.
How to encapsulate reusable Axios POST request function
Apr 28, 2026 am 04:38 AM
This article explains how to correctly encapsulate the axios.post request into a reusable function. The core is to explicitly return the Promise instance to avoid interruption of the call chain and Cannot read properties of undefined (reading 'then') errors due to omission of return.
How to display variable content correctly in textarea
Apr 22, 2026 am 04:42 AM
This article explains in detail how to dynamically insert PHP variable values into HTML textarea elements, focusing on correcting the common errors of "nesting span tags within textarea" and "misusing jQuery .html() method to set text area content", and provides a safe and standard PHP output solution.
How to correctly use Promise.all to load multiple image resources in parallel
Apr 23, 2026 am 04:00 AM
This article explains in detail why the array length returned by Promise.all is abnormal (only the last result is included), and provides a reusable image loading function implementation to ensure that each element returns a Boolean status independently, and finally obtains a complete and ordered loading result array.
How to properly handle return values from asynchronous AJAX requests
Apr 21, 2026 am 06:36 AM
The fundamental reason why return returns undefined in JavaScript is that XMLHttpRequest is an asynchronous operation. The function has been executed and returned before the response arrives. At this time, the variables assigned in the callback have not yet taken effect. You must ensure you get a true response via Promise/async-await or synchronous requests (not recommended).
How to preserve Unicode variable names (such as π) when packaging in esbuild
Apr 17, 2026 am 04:17 AM
By default, esbuild escapes non-ASCII characters (such as the Greek letter π, Chinese identifiers, etc.) into Unicode encoding (such as \u03C0). You can disable escaping through the --charset=utf8 parameter so that the Unicode identifiers in the source code are output as they are. The premise is to ensure that the running environment correctly declares UTF-8 encoding.
marked.js custom image rendering: handling non-standard syntax and path prefixes
Apr 22, 2026 pm 11:00 PM
This tutorial details how to customize image rendering behavior using the renderer option of marked.js. In response to the needs of non-standard Markdown image syntax (such as ![[filename.jpg]]) and image URL path prefixes, the article provides specific code examples and explanations to guide readers on how to achieve dynamic processing of image paths and precise generation of HTML tags by overriding the default renderer.image method to meet specific rendering requirements.





