I am trying to get a rudimentary GET request from a Node.js server when I click on a button.
server.js
const express = require('express'); const app = express(); app.use(express.static("./public")); app.listen(8080, () => { console.log(`Service started on port 8080.`); }); app.get('/clicks', (req, res) => { res.send("foobarbaz"); })
client.js
document.getElementById("button").addEventListener("click", showResult); function showResult(){ fetch('/clicks', {method: 'GET'}) .then(function(response){ if(response.ok){ return response; } throw new Error('GET failed.'); }) .then(function(data){ console.log(data); }) .catch(function(error) { console.log(error); }); }
However, the console log shows:
Response {type: "basic", url: "http://localhost:8080/clicks", redirected: false, status: 200, ok: true, …} body: (...) bodyUsed: false headers: Headers {} ok: true redirected: false status: 200 statusText: "OK" type: "basic" url: "http://localhost:8080/clicks" __proto__: Response
How can I get my “foobarbaz”?
If I go to localhost:8080/clicks
the text shows up there.
Additionally, the response
already seems to be a javascript object — response.json()
doesn’t work.
Advertisement
Answer
The send()
parameter should be a JSON. Change server.js
to
app.get('/clicks', (req, res) => { res.send({result:"foobarbaz"}); })
Now you will receive a JSON as the response in client.js
and the result can be consumed as
function showResult() { fetch('/clicks', { method: 'GET' }) .then(function (response) { if (response.ok) { return response.json(); } throw new Error('GET failed.'); }) .then(function (data) { console.log(data.result); }) .catch(function (error) { console.log(error); }); }