[英]Express: Remove charset=utf-8 from Content-Type "application/json; charset=utf-8"
I have a NodeJS and express based app.我有一个基于 NodeJS 和 express 的应用程序。 Every time I m trying to fetch a response, I m getting
Content-Type: "application/json; charset=utf-8"
.每次我尝试获取响应时,都会得到
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"
.我无法在前端解析这个,因为我期待响应头
Content-Type: "application/json"
。
I have tried res.setHeader, res.set
methods as well but nothing seems to be helpful.我也尝试过
res.setHeader, res.set
方法,但似乎没有任何帮助。 Any advice is appreciated.任何建议表示赞赏。
Following is my express code:以下是我的快速代码:
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")));
My Front end call is as follow:我的前端调用如下:
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 will set the charset for you. Express 将为您设置字符集。 So if you want to bypass it, don't use express methods, since
res
extends from: http.ServerResponse
you can use .writeHeader
& .write
.所以如果你想绕过它,不要使用 express 方法,因为
res
扩展自: http.ServerResponse
你可以使用.writeHeader
& .write
。
The res object is an enhanced version of Node's own response object and supports all built-in fields and methods.
res 对象是 Node 自己的响应对象的增强版,支持所有内置的字段和方法。
res.writeHead(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.无论如何,最好添加字符集,我建议您改为在前端进行更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.