繁体   English   中英

如何从我的快速服务器获取 json 数据?

[英]How do I get json data with fetch from my express server?

我一直在尝试使用 fetch 从我的快速服务器获取 JSON 数据。 但是,它不起作用。 我已经用JSONPlaceholder测试了 fetch 函数,所以我认为我的快速代码是问题所在。

这是我的提取代码:

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

这是我的快递代码:

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

谢谢!

 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) })

试试这个,因为 RequestOptions 很重要,它告诉我们发送到服务器的请求类型

而不是res.json使用res.send

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

我还建议处理异常并且不要使用return因为它只会在 fetch 请求中导致错误:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM