You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js接收POST请求时无法设置Content-Type为application/json的问题

Troubleshooting JSON POST Issues Between Chrome Extension and Node.js Server

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 fetch or XMLHttpRequest, you can’t just pass a plain JavaScript object as the request body—you need to convert it to a JSON string with JSON.stringify().
  • Double-check the Content-Type header: Ensure it’s explicitly set to application/json (typos like application/json; charset=utf-8 are okay, but the core value needs to match).
  • Confirm extension permissions: In your manifest.json, make sure you’ve added the server’s domain to host_permissions so 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:

  1. Open DevTools (F12) and go to the Network panel.
  2. Trigger the POST request from your extension.
  3. Click on the request entry to view details:
    • Check the Request Headers tab to confirm Content-Type: application/json is present.
    • Check the Request Payload tab to verify the body is a valid JSON string (not form data or a raw object).

This will tell you if the problem is on the client side (bad request) or server side (failed parsing).

内容的提问来源于stack exchange,提问作者netsocket

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:58:31