skip to Main Content

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:

  1. Two different approaches to parse JSON
  2. Use a different host for JSON

2

Answers


  1. Chosen as BEST ANSWER

    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.

    const headers = {
        'Access-Control-Allow-Origin': '*', /* @dev First, read about security */
        'Access-Control-Allow-Methods': 'OPTIONS, GET',
        'Access-Control-Max-Age': 2592000, // 30 days
        'Content-Type': 'application/json; charset=utf-8'
        /** add other headers as per requirement */
    };
    

  2. res is a Response, not the text. Use res.json() to parse the body text as JSON.

    fetch('http://localhost:64567').then(res => res.json())
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search