I am trying to make a low dependency JavaScript to show temperature of raspberry pi. The server sends a JSON as a response to get request and the Client shows a web page.
The server is working as intended,I have checked in browser and using postman
const { spawn } = require("child_process");
const http = require('http');
http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
const temp = spawn('cat', ['/sys/class/thermal/thermal_zone0/temp']);
temp.stdout.on('data', function (data) {
data = data / 1000;
console.log('Temperature: ' + data + '°C');
res.end(JSON.stringify({"temp":data}));
});
temp.stderr.on('data', function (data) {
res.end(JSON.stringify({"temp":"Unavailable"}));
});
}
else {
res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({"temp":"Unavailable"}));
}
}).listen((process.argv[2] || 64567), () => {
console.log('Server listening on http://localhost:' + (process.argv[2] || 64567));
});
This is the client side code
<body>
<script defer>
await fetch('http://localhost:64567',{mode: 'no-cors'}).then(res => JSON.parse(res)).then(temp => document.getElementById("value").innerHTML = temp.temp);
// SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
/*
await fetch('http://localhost:64567',{mode: 'no-cors'}).then(res => res.json()).then(temp => document.getElementById("value").innerHTML = temp.temp)
// SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
await fetch('https://api.npoint.io/d5a7160bab77dd869b82').then(res => res.json()).then(temp => document.getElementById("value").innerHTML = temp.temp)
// This one works
*/
</script>
<h3>Temperature:<span id="value"> </span> °C</h3>
</body>
but when I try to use fetch api in the client side, JSON.parse gives two different types of errors for different approaches, but when I use a publicly hosted JSON bin it works.
Expectation: Fetch JSON being fetched and parsed correctly.
Tried:
- Two different approaches to parse JSON
- Use a different host for JSON
2
Answers
So I figured it out, thanks to @Unmitigated , all I needed to do was set the CORS on the server side and remove
mode:no-cors
in the client side.Adding headers like these, in the server was the fix.
res
is aResponse
, not the text. Useres.json()
to parse the body text as JSON.