代码之家  ›  专栏  ›  技术社区  ›  Pranay Tripathi

Express:从内容类型“application/json;charset=utf-8”中删除charset=utf-8

  •  0
  • Pranay Tripathi  · 技术社区  · 5 年前

    我有一个基于NodeJS和express的应用程序。每次我试图得到回应,我都会得到 Content-Type: "application/json; charset=utf-8" . 我无法在前端分析此内容,因为我期望的是带有头的响应 Content-Type: "application/json" .

    我试过了 res.setHeader, res.set 方法也一样,但似乎没有任何帮助。任何建议都很感激。

    以下是我的快速代码:

    const app = express();
    
    configureMongoClient();
    
    app.use(logger("dev"));
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
    app.use(cookieParser());
    app.options('*', cors())
    
    app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    
    app.use((req, res, next) => {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET, PUT, POST');
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, X_BPI_CONTEXT');
        res.header("Content-Type", "application/json")
        next();
    });
    app.use("/users", usersRouter);
    app.use(express.static(path.join(__dirname, "public")));
    

    我的前端呼叫如下:

    fetch(uri, {
        method: "POST",
        headers: {
          Content-Type: "application/json"
        },
        body: JSON.stringify(requestData),
      })
        .then((response) => {
          debugger;
          return response.json()
        }) .then((data) => {
            console.log(data);
          });
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   Marcos Casagrande    5 年前

    快递会为您设置字符集。所以如果你想绕过它,不要使用express方法,因为 res 扩展自: http.ServerResponse 你可以用 .writeHeader &安培; .write .

    res对象是节点自身响应对象的增强版本 并支持所有内置字段和方法。

    res.writeHeader(200, { 'Content-Type': 'application/json' })
    res.write(JSON.stringify(object))
    res.end()
    

    无论如何,最好添加字符集,我建议您在前端进行更改。