问题
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"
.
I have tried res.setHeader, res.set
methods as well but nothing seems to be helpful. 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);
});
回答1:
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
.
The res object is an enhanced version of Node’s own response object and supports all built-in fields and methods.
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.
来源:https://stackoverflow.com/questions/59449221/express-remove-charset-utf-8-from-content-type-application-json-charset-utf-8