M
M
Mothersprogrammer2020-08-23 14:28:34
JavaScript
Mothersprogrammer, 2020-08-23 14:28:34

Why does the Unexpected end of JSON input error occur?

There is a method:

postJson(data){
            return fetch('/todo.json', {
                method: 'POST',
                body: JSON.stringify(data),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
              .then(response => response.json())
              .then(function(response) {
                  console.info('fetch()', response);
                  return response;
              });
                
        },


here is how it is called:
this.postJson(this.todos)
              .then(()=>{
                console.log(this.todos)
              })

further, according to the plan, all data should go to node, and be written to json there, deciding to remove part of the code with changing json, an error appeared that the file was not found, so it seems to me that the problem may be hiding in the node code, here it is:
const express = require('express');
const fs = require("fs");
const app = express();

app.use('/', express.static('dist'));

app.post('/todo.json', (req, res) => {
    fs.watchFile('/todo.json', req, (err)=>{
        throw err
    })
    res.end();
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listen on port ${port}...`));


Here is the text of the error Uncaught (in promise) SyntaxError: Unexpected end of JSON input
Please tell me where I made a mistake in the code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kocherman, 2020-08-23
@kocherman

Apparently, the server is sending an empty response to the browser, which is expecting a json response.
Replace the line
res.end();
with
res.end("{}");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question