I am making an Express application that takes in (binary) post data. Here is my code below.
Server-side:
var express = require('express');
var app = express();
var PORT = 3000;
app.use(express.raw());
app.post('/', function(req, res) {
console.log(req.body);
res.end();
});
app.get('/', function(req, res) {
res.sendFile(__dirname '/index.html');
});
app.listen(PORT, function() {
console.log("Server listening on port", PORT);
});
index.html:
<script>
fetch("/", {
method: "POST",
body: "hello world",
});
</script>
However, when I run this code, when logging the request body, it logs an empty object. And when I looked at the documentation, it says that the request body will be an empty object if there was no body to parse. But I had a body in the request. What am I doing wrong here?
CodePudding user response:
For express.raw()
to parse, add "Content-Type": "application/octet-stream"
inside headers
in your fetch()
. Like so:
fetch("/", {
method: "POST",
body: "hello world",
headers: {
"Content-Type": "application/octet-stream",
},
});
CodePudding user response:
express.raw()
only works if you set your Content-Type
header in your fetch to `application/octet stream. So your new fetch method would look like this.
fetch("/", {
method: "POST",
body: "hello world",
headers: {
"Content-Type": "application/octet-stream"
}
});
But what if you don't want the content type to be application/octet-stream
? In this case, you can specify in the express.raw()
options that the content type to parse the body can be any type. How to do this? Replace this:
app.use(express.raw());
With this:
app.use(express.raw({type: '*/*'}));
The type
option is the needed content type for body-parser
to parse the body, and the */*
means that any content type will be accepted.
CodePudding user response:
Use this for your usecase
app.use(express.text());