本文介绍了表达:从Content-Type"application/json;中删除charset = utf-8; charset = utf-8";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于NodeJS和Express的应用程序.每次尝试获取响应时,我都会得到Content-Type: "application/json; charset=utf-8".我无法在前端解析此消息,因为我期望标题为Content-Type: "application/json"的响应.

I have a NodeJS and express based app. Every time I m trying to fetch a response, I m getting Content-Type: "application/json; charset=utf-8". I m unable to parse this on front end as I m expecting response with header Content-Type: "application/json".

我也尝试过res.setHeader, res.set方法,但是似乎没有任何帮助.任何建议表示赞赏.

I have tried res.setHeader, res.set methods as well but nothing seems to be helpful. Any advice is appreciated.

以下是我的明确代码:

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);
      });

推荐答案

Express会为您设置字符集.因此,如果您想绕过它,请不要使用express方法,因为res是从http.ServerResponse扩展而来的,您可以使用.writeHeader& .write.

Express will set the charset for you. So if you want to bypass it, don't use express methods, since res extends from: http.ServerResponse you can use .writeHeader & .write.

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

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

In any case, it's better to add the charset, and I suggest you do the changes in the front end instead.

这篇关于表达:从Content-Type"application/json;中删除charset = utf-8; charset = utf-8";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:46
查看更多