Home > other >  How do I get json data with fetch from my express server?
How do I get json data with fetch from my express server?

Time:10-30

I’ve been trying to use fetch to get JSON data from my express server. However, it doesn’t work. I’ve tested the fetch function with JSONPlaceholder so I think my express code is the problem.

Here is my fetch code:

fetch("https://myexpressserver.com/api/example")
    .then(response=> {
        return response.json()
    })
    .then(data=> {
        console.log(data.text);
    })

And here is my express code:

app.get('/api/example', function(req, res){
    res.json({ text: 'This is what you should get if this works' });
});

Thank you!

CodePudding user response:

const RequestOptions = {
        method: 'GET',
        headers: {'Content-Type': 'application/json' },
    };
fetch("https://myexpressserver.com/api/example",RequestOptions).then(Response=> Response.json()).then((data)=>{
           console.log(data.txt)
            })
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

try this because RequestOptions is important it tell what type of request we send to server

CodePudding user response:

Instead of res.json use res.send!

app.get('/api/example', function(req, res){
    res.send({ text: 'This is what you should get if this works' });
});

I also recommend to handle exception and don't use return as it will only cause error in the fetch request:

fetch("https://myexpressserver.com/api/example")
    .then(response=> {
        response.json();
    })
    .then(data=> {
        console.log(data.text);
    })
    .catch(err =>{
         console.error(err);
    })
  • Related