0

Objective: provide some basic data from Express JS to browser requests, all running locally on localhost.

When I connect to the URL (http://localhost/test) with the browser directly I see the data I'm trying to receive in the browser window. However, when I execute the following code in a tag in an HTML document I get "Uncaught (in promise) SyntaxError: Unexpected end of input" and no data retrieved.

        fetch('http://localhost/test', {
        'content-type': 'application/json',
        mode: 'no-cors',
        method: 'GET',
        redirect: 'follow'
    })
        .then(response => response.json())
        .then(json => console.log(json))

Here's my Express code:

    app.get("/test", (req, res) => {
        res.header(
            "Access-Control-Allow-Origin","http://localhost:*"
        )
        res.json( {username: 'Joe'})
    });

I started without the "res.header" above but after many searches found that as a suggestion. CURL and XMLHttpRequest both work fine.

Baron Young
  • 181
  • 2
  • 13
  • 1
    Sounds like the server is returning an empty JSON response. Use the Network tab of the browser to see what's being returned. – Barmar Apr 05 '22 at 01:29
  • I think you're right - it is returning an empty response. What I can't figure out is why. Both CURL and XMLHttpRequest can send a request and get a JSON response just fine. For some reason fetch is unable to do this. For now I'm just tossing fetch and using XMLHttpRequest. Thanks. – Baron Young Apr 05 '22 at 19:17
  • Are there any errors in the console when the fetch is done? I can't think of a reason why fetch would fail when `XMLHttpRequest` succeeds. – Barmar Apr 05 '22 at 19:24
  • Yeah it's the error in the title of this post. – Baron Young Apr 07 '22 at 00:39

1 Answers1

0

I've seen something somewhat related recently. I think the problem might be that you are using a no-cors mode, which expects an opaque response. I'm no specialist in the matter but I suggest you check the link I shared.

I had a similar issue in vanilla JS and a REST API running on Azure (Function App). In my JS code, I removed the no-cors mode for the request; and in the REST API providing the response, I changed the allowed origins to * wildcard. Hope it's of any help.

michal
  • 67
  • 7