'app.post pass objects from express server to html?
how do I pass objects from server to html?
I have my nodejs code here below that I stripped off details to keep it simple.
nodejs.js
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(bodyParser.json());
app.post('/',urlencodedParser, function(req, res) {
Object = new Class();
res.status(200).json(Object);
});
Here is my js code called by html.
myjs.js
function fetcher() {
fetch('/',
{
method: "POST",
body: JSON.stringify({"name": document.getElementById("name").value}),
headers: { "Content-Type": "application/json" }
}
)
.then(function(response) {
return response.json();
})
.then(function(Obj) {
console.log(obj.func());
});
}
Solution 1:[1]
- The body-parser package is redundant. All the previous middleware is available in Express already via express.json(), express.urlencoded(), etc.
- If you're expecting a JSON request body, don't use the
urlencodedmiddleware directly in your route handler. Objectis a reserved word. You should not name any variables or symbols (classes, functions, etc) using it- In order to respond with JSON, whatever object you're passing needs to be serialisable. This can be customised via a
toJSON()method.
class SomeClass {
constructor(name) {
this.name = name;
}
// customise JSON serialisation
toJSON() {
return { name: this.name };
}
}
app.use(express.json());
app.post("/", (req, res) => {
const obj = new SomeClass(req.body.name);
res.json(obj); // no need for `status(200)`, it's implied
});
On the client-side, JSON is a string format. Functions and methods cannot be represented. All you will have is data
fetch("/", {
method: "POST",
body: JSON.stringify({ name: document.getElementById("name").value }),
headers: { "Content-Type": "application/json" },
})
.then((res) => (res.ok ? res.json() : Promise.reject(res)))
.then((obj) => {
console.log(obj); // no `.func()` here
})
.catch(console.error);
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 |
