Reputation: 173
I am trying to send a string from a client side page to a server, but the server receives an empty object. Here is my client side code:
fetch("/sugestions/sugestions.txt", {
method: "POST",
body: JSON.stringify({ info: "Some data" }),
headers: {
"Content-Type": "application/json; charset=utf-8"
}
})
.then(res => {
if (res.ok) console.log("Yay it worked!");
else window.alert("Uh oh. Something went wrong!\n" + res);
});
This is my server side code:
const express = require("express");
const url = require("url");
const fs = require("fs");
const bodyParser = require("body-parser");
const app = express();
const port = process.env.PORT || 8080;
app.set("view engine", "ejs");
app.use(bodyParser());
app.post("/sugestions/*", (req, res) => {
info = JSON.parse(req.body);
fs.appendFile(path("req").pathname, info.info, (err) => {
if (err) res.status(404).end();
else res.status(200).end();
});
});
app.listen(port);
Here is the path function, in case that matters:
const path = req => url.parse(`${req.protocol}://${req.get("host")}${req.originalUrl}`, true);
Upvotes: 1
Views: 1800
Reputation: 1
Since express 4.16.0 you can use app.use(express.json());
to get the json data from request,in your case it would be.You don't require to use bodyparser and all.
const express = require("express");
const url = require("url");
const fs = require("fs");
const bodyParser = require("body-parser");
const app = express();
const port = process.env.PORT || 8080;
app.set("view engine", "ejs");
app.use(express.json())// add this line
app.post("/sugestions/*", (req, res) => {
info = JSON.parse(req.body);
fs.appendFile(path("req").pathname, info.info, (err) => {
if (err) res.status(404).end();
else res.status(200).end();
});
});
app.listen(port);
Upvotes: 2
Reputation: 2420
To access the body of a request you need to use bodyParser. And you need to explicitly tell your bodyParser about the data formats that you need to parse. Now coming to your solution, Replace
app.use(bodyParser());
with
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Upvotes: 1
Reputation: 78
Add this two line to your code
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Upvotes: 0