Node.js接收POST请求时无法设置Content-Type为application/json的问题
Hey there, let’s work through this problem together—this is a super common gotcha when sending JSON from Chrome extensions to Node.js servers, so I’ve got a few key checks and fixes to share.
First, Verify Your Chrome Extension’s Request Code
The most frequent culprit here is not properly serializing your data or misconfiguring the request headers. Let’s make sure you’re doing both right:
- Always serialize your JSON data: If you’re using
fetchorXMLHttpRequest, you can’t just pass a plain JavaScript object as the request body—you need to convert it to a JSON string withJSON.stringify(). - Double-check the
Content-Typeheader: Ensure it’s explicitly set toapplication/json(typos likeapplication/json; charset=utf-8are okay, but the core value needs to match). - Confirm extension permissions: In your
manifest.json, make sure you’ve added the server’s domain tohost_permissionsso the extension is allowed to send requests to it.
Here’s a corrected example of a fetch request in your extension:
// Chrome extension background/content script const payload = { username: "test", preferences: { darkMode: true } }; fetch("http://your-node-server:3000/api/data", { method: "POST", headers: { "Content-Type": "application/json", // Add any auth headers here if needed (e.g., Authorization) }, body: JSON.stringify(payload), // Critical step: serialize the object! }) .then(response => response.json()) .catch(error => console.error("Request failed:", error));
Next, Fix Your Node.js Server’s JSON Parsing
If your server is receiving data but it’s not in JSON format, chances are it’s not set up to parse JSON request bodies correctly:
For Express.js Users
You need to use the built-in express.json() middleware before your route handlers. This middleware automatically parses incoming JSON payloads into a JavaScript object accessible via req.body.
// Node.js Express server const express = require("express"); const app = express(); // Mount the JSON parser middleware FIRST app.use(express.json()); // Your POST route app.post("/api/data", (req, res) => { console.log("Received JSON data:", req.body); // This should now be a valid object res.status(200).json({ status: "success", received: req.body }); }); app.listen(3000, () => console.log("Server running on port 3000"));
For Native http Module Users
If you’re not using Express, you’ll need to manually read and parse the request body:
const http = require("http"); const server = http.createServer((req, res) => { if (req.method === "POST" && req.headers["content-type"] === "application/json") { let rawBody = ""; // Collect the request data chunks req.on("data", (chunk) => { rawBody += chunk.toString(); }); // Once all data is received, parse it req.on("end", () => { try { const parsedData = JSON.parse(rawBody); console.log("Parsed JSON:", parsedData); res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ success: true, data: parsedData })); } catch (error) { // Handle invalid JSON res.writeHead(400, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "Invalid JSON payload" })); } }); } else { res.writeHead(404); res.end(); } }); server.listen(3000);
Debug with Chrome DevTools
If you’re still stuck, use Chrome’s Network tab to inspect the actual request being sent:
- Open DevTools (F12) and go to the Network panel.
- Trigger the POST request from your extension.
- Click on the request entry to view details:
- Check the Request Headers tab to confirm
Content-Type: application/jsonis present. - Check the Request Payload tab to verify the body is a valid JSON string (not form data or a raw object).
- Check the Request Headers tab to confirm
This will tell you if the problem is on the client side (bad request) or server side (failed parsing).
内容的提问来源于stack exchange,提问作者netsocket

