I have a simple express app,
// index.js
import express from "express";
// create the express application
const app = express();
app.use(express.json());
// serve static files
app.use(express.static("./"));
// set builtins post
app.post("/builtins", (req, res) => {
console.log("debug request body builtins", req.body);
res.sendStatus(200);
});
// start the server
app.listen(3333, () => console.log("Start express app"));
And a simple index.html
page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ExpressApp</title>
</head>
<body>
<script>
fetch("http://localhost:3333/builtins", {
body: JSON.stringify(["wojtyla", "ratzinger", "madre teresa"]),
mode: "no-cors",
headers: {
"Content-Type": "application/json",
},
method: "POST",
})
.then((t) => t.text())
.then((t) => document.write(`<h1>Got response ${t}</h1>`));
</script>
</body>
</html>
I start the server as usual: node index.js
. Then open a browser at http://localhost:3333/index.html
.
Everything seems to be ok, but when I open the logs of the express app, I check the following:
debug request body builtins {}
But I was expecting to receive:
debug request body builtins [ 'wojtyla', 'ratzinger', 'madre teresa' ]
The strange part in this is that when I curl:
curl -d '["wojtyla","ratzinger", "madre teresa"]' "Content-Type: application/json" -X POST http://localhost:3333/builtins
I receive the expected answer in the express app logs (debug request body builtins [ 'wojtyla', 'ratzinger', 'madre teresa' ]
).
What am I doing wrong here? Can someone help me?
Thanks in advance
CodePudding user response:
You said:
mode: "no-cors",
Which tells fetch
that if you try to do anything that requires permission from the server (using CORS) then it should fail silently.
Setting the content-type
to anything that isn't a supported value of the HTML form
element's enctype
attribute is one of those things.
Since you fail to set the content-type
request header, the browser isn't telling the server it is sending application/json
, so the JSON parsing middleware doesn't kick in.
- Don't use
mode: "no-cors",
on the client - Do use the
cors
middleware on the server.