Reputation: 245
How can I get { data: data }
on the client using fetch()
from the res.render ()
or res.json()
methods of the server?
1) rendered page
2) fetch()
is called, data (data) came from the server
3) I want to manipulate them in the DOM
data comes, but they redraw the page and I see the json
structure
Server.js
let PORT = process.env.PORT || 5000;
const express = require('express');
const app = express();
const server = require('http').createServer(app);
// not matter
app.set('views', './views');
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(express.json());
// this
const data = {
array: [1, 2, 3],
string: 'string'
};
app.get('/', function(req, res) {
res.json(data)
});
index.ejs(html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
fetch('/')
.then(res => {
return res.json();
})
.then(obj => console.log(obj));
</script>
</body>
</html>
Upvotes: 1
Views: 289
Reputation: 245
My code is working correctly.
The problem is that I am taking data from where I am.
Example: I am on this page - localhost:5000/
, and trying to get data from the same place:
app.get(/, function (req, res ) {
res.json(data);
})
and it turns out that first I get the data from the server and the res.json(data)
method sends it and draws this data on the page, and that's all, nothing more.
If I need to get something, I would prescribe:
app.get(/data, function (req, res ) {
res.json(data);
});
app.get('/', function(req, res) {
res.send('index');
});
const data = {
array: [1, 2, 3],
string: 'string'
};
app.get('/data', function(req, res) { // <---
res.json(data);
});
fetch('/data').then(res => res.json())
.then(obj => console.log(obj));
We start the server, go to the localhost/
, open the console, and bam!
Upvotes: 0
Reputation: 707158
When you do this:
fetch("/", {method: "get"}).then(res => {
console.log(res);
});
You will find that res
is a BODY object which contains a readable stream and the data in that stream has not yet been read (only the headers have been read). So, to get that data, you have to use one of the methods that reads it depending upon what type of data you are expecting.
res.json()
res.text()
res.formData()
res.blob();
res.arrayBuffer();
These are all asynchronous methods that also return a promise. So, if you just want text:
fetch("/", {method: "get"}).then(res => res.text()).then(text => {
console.log(text);
});
Upvotes: 2