'Express server returning an empty body from a post request
I've been working on a project with express, and have a post request set up. However, it returns an empty body on the response, but it appears to be working otherwise. Here's the server:
const express = require('express');
const app = express();
const http = require('http').Server(app);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.raw());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.use("/public", express.static(__dirname + "/public"));
http.listen(8080, '0.0.0.0' , function() {
console.log('listening on localhost:8080');
});
app.post('/form', (req, res) => {
console.log(req.body);
res.end('bla bla bla');
// I've also tried res.json and res.send
});
And here's the client:
fetch("/form", {method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify({bla: "bla"})}).then((thing) => {
console.log(thing);
console.log(thing.json());
console.log(thing.body);
});
This seems like it should work, but instead it returns this object:
Response
body: (...)
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:8080/form"
[[Prototype]]: Response
I can't seem to find where the error lies, or even whether it's working and I just don't know how to get the data from it.
Solution 1:[1]
I've figured it out! It turns out that my code was working all along, it's just that I had messed up the fetch request. What I should have done client-side was:
fetch("/form", {method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify({bla: "bla"})})
.then(res => res.json())
.then(data => console.log(data));
I was missing the second .then() and that was throwing it off.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TheLazySquid |