-1

On my client side, I simply want to aler the response I get from the server.

function displayItems()
{
    fetch('http://ip_address:3000/users',{
        method:'POST',
        headers:{
            'Accept':'application/json',
            'Content-Type':'application/json',
        },
        mode:'no-cors'
    })
    .then((response) => {return response.json();})
    .then((res) => { alert(res.message)})
}

On my server side, I have this simple code to respond to request

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.post('/', function(req, res, next) {

  let obj = {message:'fsdfsdfsdfsd'}
  res.send(obj);

  console.log('server Reached')
});

module.exports = router;

After looking up other related problems, I am still unable to resolve this error: Uncaught (in promise) SyntaxError: Unexpected end of input.

Thank you in advance to those who look at this.

Patrick Adjei
  • 115
  • 3
  • 12

1 Answers1

3

In addition to the no-cors problem Quentin pointed out with the duplicate (which he answers here), there are several other issues:

What you're sending isn't JSON:

res.send('Hello world'); // <=== This is plain text

...so response.json() would fail when trying to parse the response.

If you're just sending text like that, you'd use response.text() to read it instead of .json().

You're also not checking correctly for HTTP errors. It's not just you, almost everyone makes this mistake (which I've written up here), it's a flaw (IMHO) in the fetch API. To correctly check for errors and receive text (rather than JSON), see *** comments:

function displayItems()
{
    fetch('http://172.30.117.7:3000/users',{
        method:'POST',
        headers:{
            'Accept':'application/json',
            'Content-Type':'application/json',
        },
        mode:'no-cors'
    })
    .then((response) => {
        // *** Check for HTTP failure
        if (!response.ok) {
            throw new Error("HTTP status " + response.status);
        }
        // *** Read the text of the response
        return response.text();
    })
    .then((message) => {
        // *** Use the text
        alert(message);
    })
    .catch((error) => {
        /* ...*** handle/report error, since this code doesn't return the promise chain...*/
    });
}

Alternately, if you wanted, you could send back JSON:

response.json({message: "Hi there"});

...and then on the client:

function displayItems()
{
    fetch('http://172.30.117.7:3000/users',{
        method:'POST',
        headers:{
            'Accept':'application/json',
            'Content-Type':'application/json',
        },
        mode:'no-cors'
    })
    .then((response) => {
        // *** Check for HTTP failure
        if (!response.ok) {
            throw new Error("HTTP status " + response.status);
        }
        // *** Read and parse the JSON
        return response.json();
    })
    .then((res) => {
        // *** Use the object
        alert(res.message);
    })
    .catch((error) => {
        /* ...*** handle/report error, since this code doesn't return the promise chain...*/
    });
}

But again, all of that is aside from the primary problem Quentin pointed out with the duplicate.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    If `Hello World` was the issue, it would complain that `H` was invalid JSON. It's failing with unexpected end of content because of the no-cors mode. – Quentin Oct 23 '19 at 18:14
  • @Quentin - Thanks, I guess the error would be different, wouldn't it? All of the above still applies, so I've marked it CW and called out that these are *separate*, additional issues. Thanks again! – T.J. Crowder Oct 23 '19 at 18:19
  • That was stupid of me. I modified my code. Essentially I and trying to print the key value pair of the object. – Patrick Adjei Oct 23 '19 at 19:39
  • @Quentin Sorry for the first code, I initially wanted to send an object as a message. I added the checks and the I changed 'no-cors' to 'cors'. I get this error now 'from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.' How can I make the server allow for reading the response using the Access-Control-Allow-Origin header – Patrick Adjei Oct 23 '19 at 21:32
  • @Quentin The Following code was added:app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); res.setHeader('Access-Control-Allow-Credentials', true); next(); }); and I still get the CORS policy error. Please help me – Patrick Adjei Oct 23 '19 at 21:54
  • @PatrickAdjei - You should be able to find solutions for CORS in Express using [this search](/search?q=%5Bexpress%5D+cors). – T.J. Crowder Oct 24 '19 at 06:00
  • @T.J.Crowder I understood and found the solution to my problem. Thank you – Patrick Adjei Oct 25 '19 at 02:34