0

I face a new problem that has been asked before in this link. But It is not relevant to my problem.

What I have implemented is a very simple API using nodejs, express-framework and mongoose. The problem is with fetch API. I want to submit some ID and post it to the server. In the server side I redirect it to the proper URL base on the ID that user entered. Whenever I test this part, this error is being raised in front-end side and points to return response.json() line.

SyntaxError: Unexpected end of input

Here is my code:

Front-End:

function submitCode(){
    var nationalCode = document.getElementById('nationalCode').value
    var data = {
        nationalCode: nationalCode,
        creationDate: new Date().toLocaleDateString()
    }

    fetch('/submit', {
        method: 'POST',
        redirect:'manual',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify(data)
    },
    ).then(response => {
        return response.json()
    }).then(jsonData => {
        console.log('success:', jsonData)
        history.pushState(null, null, "/lashkhor")
    }).catch(e => {
        console.log('error:', e)
        return e
    })
}

Back-End:

app.post('/submit', (req, res) => {
    var nationalCode = req.body.nationalCode
    var creationDate = req.body.creationDate

    query = {'nationalCode': nationalCode}
    nationalCodeModel.find(query, (err, success) => {
        if (err) {
            console.log('error:', err)
        }
        else if (success.length == 0){
            nationalCodeModel.create({
                nationalCode: nationalCode,
                creationDate: creationDate
            })
            console.log('salam khoshgele daei!')
            res.redirect('/khoshgeledaei')
        }
        else if (success.length > 0) {
            console.log('lashkhor detected')
            res.redirect('/lashkhor')
        }
    })

})

app.get('/lashkhor', (req, res) => {
    console.log('here')
    res.send('salam')
})

I can't find any hint to solve it. I would be thankful if anyone could help me.

PS: Whole code is available in this repository

Thanks!

jcoleau
  • 1,112
  • 7
  • 20
Mostafa Ghadimi
  • 5,883
  • 8
  • 64
  • 102

1 Answers1

1

You are trying to parse text into json. You can use res.json() instead of res.send() from your backend.

jcoleau
  • 1,112
  • 7
  • 20
  • 1
    In your frontend: `.then(response => { return response.json() })` response.json fails because the response from the server is not JSON. – geekonaut Apr 01 '20 at 21:22