如何将FormData对象转换为Raw格式?Postman请求相关技术问询
Hey there! I’ve dealt with this exact issue before—getting FormData to play nice as a raw request body can be tricky if you’re not using the right approach. Let’s break down the solutions based on what kind of "Raw" format you’re targeting in Postman (since Raw can mean x-www-form-urlencoded, JSON, or plain text):
1. Convert to x-www-form-urlencoded Raw String (Most Common for Form Data)
If your working Postman request uses Raw with application/x-www-form-urlencoded content type, here’s how to do it correctly (your earlier attempts with form-urlencoded or encodeURI might have failed because you passed the FormData object directly instead of a plain JS object):
Option A: Use Native URLSearchParams (No Third-Party Packages)
This is the simplest, no-install method:
// Your existing FormData object const formData = new FormData(); formData.append('username', 'Tiago'); formData.append('password', 'secure123'); // Convert directly to x-www-form-urlencoded string const rawBody = new URLSearchParams(formData).toString(); console.log(rawBody); // Output: username=Tiago&password=secure123
Option B: Fix Usage of form-urlencoded NPM Package
If you prefer using the package, you need to first convert FormData to a plain object:
const formUrlEncoded = require('form-urlencoded'); const formData = new FormData(); formData.append('username', 'Tiago'); formData.append('password', 'secure123'); // Convert FormData to a plain JavaScript object const formObj = {}; formData.forEach((value, key) => { formObj[key] = value; }); // Now encode the object to x-www-form-urlencoded string const rawBody = formUrlEncoded(formObj); console.log(rawBody); // Output: username=Tiago&password=secure123
2. Convert to JSON Raw String
If your Postman Raw request uses application/json content type, convert FormData to a plain object first, then stringify it:
const formData = new FormData(); formData.append('username', 'Tiago'); formData.append('password', 'secure123'); // Convert FormData to plain object const formObj = {}; formData.forEach((value, key) => { formObj[key] = value; }); // Stringify to JSON raw body const rawJsonBody = JSON.stringify(formObj); console.log(rawJsonBody); // Output: {"username":"Tiago","password":"secure123"}
Critical Reminder: Set the Correct Request Header
Don’t forget to match the Content-Type header to your raw format:
- For x-www-form-urlencoded:
Content-Type: application/x-www-form-urlencoded - For JSON:
Content-Type: application/json
Postman automatically sets this when you select the Raw format, but you’ll need to manually add it to your request code.
内容的提问来源于stack exchange,提问作者Tiago Castro

